List comprehensions are a convenient way to generate lists.
Here’s a simple example.
numbers = [x for x in range(10)]
print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Note that the syntax used is like a for loop, except we have to also place the loop variable at the start to specify what should actually be added to the list.
We can easily change what we add to the list. You don’t even have to use the loop variable at all if you don’t want to.
numbers = [x**2 for x in range(10)]
print(numbers)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Skipping Items
We can use an if after the loop to skip items. Here we only add an item from the loop to the list if there is a remainder when the number is divided by 2.
numbers = [x for x in range(10) if x % 2]
print(numbers)
[1, 3, 5, 7, 9]
Note that zero is treated as False in Python, when used in a context where a boolean is expected, and positive integers are treated as True.
Changing What Gets Added
By using an if-else at the start of the list comprehension, we can change what we add to the list, depending on the value of the loop variable.
numbers = ['odd' if x % 2 else 'even' for x in range(10)]
print(numbers)
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Leave a Reply