Python Lesson 18: List Comprehensions

  1. Create a List Comprehension
  2. Create a list using a List comprehension that has a filter

List comprehensions are an alternative to using for loops and lambda functions (next section). They are an elegant and concise way to define and create lists based on existing list or string. The syntax of a list comprehension Is as follows:

Lets say you have a list of sequential numbers from 0 to 10 and you wanted to create a new list that has all the numbers in the original list with +5 added to each item.

You could use a for loop for this purpose:

newnums =[]
nums = [0,1,2,3,4,5,6,7,8,9,10]
for x in nums:
    newnums.append(x + 5)
print(newnums)
Notebook Output

You could also use a list comprehension.

1) Create a List Comprehension

List comprehensions process faster and are more concise.

newnums = [x + 5 for x in nums]
print(newnums)
Notebook Output

2) Create a list using a List comprehension that has a filter

nums = [0,1,2,3,4,5,6,7,8,9,10]
#add 5 only to even numbers
newnums = [x + 5 for x in nums if x%2==0]
print(newnums)
Notebook Output

Recommended Books