Python - List Comprehensions
Last Updated: 1618Z 23SEP19
(Created: 1618Z 23SEP19)
Use list comprehensions to replace for loops, map(), and filter() methods.
Signatures:
new_list = [expression for_loop one_or_more_conditions]
Examples:
# Finding Squares
numbers = [1, 2, 3, 4]
squares = [n**2 for n in numbers]
print(squares) # output: [1, 4, 9, 16]
# Iterate over strings
list_in = ['Hello', 'World', 'In', 'Python']
list_lower = [str.lower() for str in list_in]
print(list_lower) # output: ['hello', 'world', 'in', 'python']
# Produce list of lists
numbers = [1, 2, 3]
square_cube_list = [[n**2, n**3] for n in numbers]
print(square_cube_list) # output: [[1, 1], [4, 8], [9, 27]]
# Filter Elements
numbers = [3, 4, 5, 6, 7]
filtered = [n for n in numbers if n > 5]
print(filtered) # output: [6, 7]
References: