Python: List Comprehension
What is List Comprehension
List Comprehension is a special syntax for building a list, or a nested list. You can use for, while, Loops to do exactly the same, but List Comprehension makes the code shorter.
Syntax
List comprehension syntax has the form
[expression for var in list]
where expression is evaluated with var replaced by each element in list.
Example
# generate a list xx = [i + 1 for i in [1, 2, 3]] print(xx) # [2, 3, 4]
Build a list of tuples:
# build a list of tuples xx = [(i, i * 2) for i in range(1, 5)] print(xx) # [(1, 2), (2, 4), (3, 6), (4, 8)]
Nested Iteration
xx = [(i, j) for i in range(2) for j in range(3)] print(xx) # [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
Python, Data Structure
- Python: List
- Python: Generate List: range
- Python: List Comprehension
- Python: List Methods
- Python: Iterate List
- Python: Map f to List
- Python: Filter List
- Python: Iterator to List
- Python: Copy Nested List, Shallow/Deep Copy
- Python: Interweave Lists to Tuples, Transpose
- Python: Sort
- Python: Convert List to Dictionary
- Python: Dictionary
- Python: Iterate Dictionary
- Python: Dictionary Methods
- Python: Tuple
- Python: Sets, Union, Intersection
- Python: Sequence Types
- Python: Read Write JSON