1. What are list comprehensions? List comprehensions construct lists in natural-to-express ways. They can replace map-filter combinations and many for loops. They’re just syntactic sugar. That means they make your code easier to read (and prettier). Example 1: For loops -> List comprehension
1 2 3 4 5 6 7 8 9 10 11 12 |
# Make a list of squares of 1 to 10 >>> squares = [] >>> for i in range(1,11): ... squares.append(i**2) ... >>> squares [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # List comprehension >>> squares_lc = [i**2 for i in range(1,11)] >>> squares_lc [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] |
Example 2: Map-filter -> List Comprehension
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Map and filter >>> doubled_odd_numbers = list(map( lambda n: n * 2, filter(lambda n: n % 2 == 1, range(1,10)) )) >>> doubled_odd_numbers [2, 6, 10, 14, 18] # List comprehension >>> doubled_odd_numbers_lc = [ n * 2 for n in range(1,10) if n % 2 == 1 ] >>> doubled_odd_numbers_lc [2, 6, 10, 14, 18] |
(I will do a post on map and filter and … Read More