01List comprehension with filter
main.py
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens)Output
[2, 4, 6]
Python comprehensions: list, dictionary, set, and generator expressions for concise and readable data transformation.
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens)[2, 4, 6]
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in matrix for x in row]
print(flat)[1, 2, 3, 4, 5, 6]
words = ["hi", "bye", "yes"]
lengths = {w: len(w) for w in words}
print(lengths){'hi': 2, 'bye': 3, 'yes': 3}nums = [1, 2, 2, 3, 3, 3]
squares = {n * n for n in nums}
print(sorted(squares))[1, 4, 9]
total = sum(x * x for x in range(1, 6))
print(total)55