May 2019
Beginner
528 pages
29h 51m
English
Here, we continue discussing functional-style features with list comprehensions—a concise and convenient notation for creating new lists. List comprehensions can replace many for statements that iterate over existing sequences and create new lists, such as:
In [1]: list1 = []In [2]: for item in range(1, 6):...: list1.append(item)...:In [3]: list1Out[3]: [1, 2, 3, 4, 5]
We can accomplish the same task in a single line of code with a list comprehension:
In [4]: list2 = [item for item in range(1, 6)]In [5]: list2Out[5]: [1, 2, 3, 4, 5]
Like snippet [2]’s for statement, the list comprehension’s for clause
for item in range(1, 6)
iterates over the sequence ...
Read now
Unlock full access