List Comprehensions
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
Syntax
[expression for item in iterable if condition]
- expression: The operation or value to include in the new list.
- item: The current element from the iterable.
- iterable: A sequence like a list, tuple, or range.
- condition (optional): A filter to include only items that meet a specific criterion.
Example
a = [2, 3, 4, 5]
squares = [val ** 2 for val in a]
a = [1, 2, 3, 4, 5]
evens = [val for val in a if val % 2 == 0]
matrix = [[1, 2, 3], [4, 5, 6]]
flat_list = [val for row in matrix for val in row]
[abs(x) for x in vec]
[weapon.strip() for weapon in freshfruit]
[(x, x**2) for x in range(6)]
vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem]