List Comprehensions

Carson West

For Loop Examples

List Comprehensions

List comprehensions provide a concise way to create lists in Python. They’re essentially a shorthand for a for loop combined with an optional conditional statement.

Basic Syntax:

new_list = [expression for item in iterable if condition]] 

Examples:

  1. Squaring numbers:
numbers = 1, 2, 3, 4, 5
squares = [x**2 for x in numbers]]  # Output: 1, 4, 9, 16, 25
  1. Filtering even numbers:
numbers = 1, 2, 3, 4, 5, 6
even_numbers = [x for x in numbers if x % 2 == 0]] # Output: 2, 4, 6
  1. String manipulation:
words = ["hello", "world", "python"]]
uppercase_words = [word.upper() for word in words]] # Output: ['HELLO', 'WORLD', 'PYTHON']]
  1. Nested List Comprehension (Nested Loops): Creating a matrix:
matrix = [i*j for j in range(3](./../i*j-for-j-in-range(3/))]] for i in range(3)]] # Output: [0, 0, 0](./../0,-0,-0/), [0, 1, 2, [0, 2, 4

Advantages:

When NOT to use List Comprehensions:

Iterable Objects