A list comprehension is a syntactical tool for creating lists in a natural and concise way, as illustrated in the following code to make a list of squares of the numbers 1 to 10:
[i ** 2 for i in range(1,11)] The dummy
i from an existing list
range is used to make a new element pattern. It is used where a for loop would be necessary in less expressive languages.
- [i for i in range(10)] # basic list comprehension
- [i for i in xrange(10)] # basic list comprehension with generator object in python 2.x
- [i for i in range(20) if i % 2 == 0] # with filter
- [x + y for x in [1, 2, 3] for y in [3, 4, 5]] # nested loops
- [i if i > 6 else 0 for i in range(10)] # ternary expression
- [i if i > 4 else 0 for i in range(20) if i % 2 == 0] # with filter and ternary expression
- [[x + y for x in [1, 2, 3]] for y in [3, 4, 5]] # nested list comprehension
List comprehensions were outlined in PEP 202 and introduced in Python 2.0.
Conditional List Comprehensions
This modified text is an extract of the original Stack Overflow Documentation created by following contributors
and released under CC BY-SA 3.0