List, Dictionary and Set Comprehensions¶
List Comprehension¶
Normal for loop that can be later done with list comprehension.
for i in range(4):
print(i*2)
Using list comprehension for the same effect.
lst = [i*2 for i in range(4)]
lst
You can make more complicated list comprehensions like multiplying only if it's a multiple of 2. I do all sorts of crazy things with list comprehensions.
lst = [i*2 for i in range(4) if i%2 == 0]
lst
Take note that this creates a list in memory where you can manipulate later. But if you do not need a list, you can use a generator expression.
Generator Expression¶
The utility of generator expressions is greatly enhanced when combined with reduction functions like sum(), min(), and max(). The heapq module in Python 2.4 includes two new reduction functions: nlargest() and nsmallest(). Both work well with generator expressions and keep no more than n items in memory at one time.
For example, we can sum the list we made above.
sum(lst)
If you do not want it in memory, simply use generator expressions.
sum(i*2 for i in range(4) if i%2 == 0)
Dictionary Comprehension¶
This is similar to what we've above, where you can use dict()
or {}
.
dict((i*2, i*4) for i in range(4) if i%2 == 0)
{i*2: i*4 for i in range(4) if i%2 == 0}
Set Comprehension¶
There are two ways to do this: set()
or {}
set(i*2 for i in range(4) if i%2 == 0)
{i*2 for i in range(4) if i%2 == 0}