fir3net

PPS-Firenetbanner-780.5x190-30-03-17

Python - List Comprehensions

List comprehensions provide an more Pythonic and alternative way (i.e instead of using map and filter) in which to express a list.
There are 3 components to a list comprehension. The expression, the for loop and the optional condition.

As you can see below, by changing the expressions and enclosing brackets to your expression you can express your list as either a list, set, list of tuples or dictionary.

>>> # LIST
>>> [x for x in range(50) if x < 25]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]

>>> # SET
>>> {x for x in range(50) if x < 25}
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24])

>>> # TUPLE
>>> [(x,x+1) for x in range(50) if x < 25]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 12), (12, 13), (13, 14), (14, 15), (15, 16), (16, 17), (17, 18), (18, 19), (19, 20), (20, 21), (21, 22), (22, 23), (23, 24), (24, 25)]

>>> # DICT
>>> {x:x+1 for x in range(50) if x < 25}
{0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10, 10: 11, 11: 12, 12: 13, 13: 14, 14: 15, 15: 16, 16: 17, 17: 18, 18: 19, 19: 20, 20: 21, 21: 22, 22: 23, 23: 24, 24: 25}