Reading 8
List Comprehensions
Why?
- Simple and elegant ways to manage lists
- Very compact
- Faster (usually) than for loops
- More flexible than for loops
Anatomy of a List Comprehension
my_new_list = [ expression for item in list ]
1) First, the expression we want carried out, in the square brackets. Here, it is expression 2) The object we want the expression working on. In this case item. 3) Last, the iterable list. Here, it is list.
Example 1
# construct a basic list using range() and list comprehensions
# syntax
# [ expression for item in list ]
digits = [x for x in range(10)]
print(digits)
prints: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Source: click here
Example 2
# create a list using list comprehension
squares = [x**2 for x in range(10)]
print(squares)
prints: [ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]
Source: click here
Example 3
Strings in a list may also be manipulated by the expression:
my_list = ["Hello World"]
yell = [letter.upper() for letter in my_list]
print(yell)
prints: ["HELLO WORLD!"]
More Complexity, More Power
Example 4
Here we can assign different object variables ( x and y ) to different lists, and use them in an expression.
nums = [x+y for x in [1,2,3] for y in [10,20,30]]
print(nums)
prints: [11, 21, 31, 12, 22, 32, 13, 23, 33]