...

/

List Comprehensions

List Comprehensions

We'll cover the following...

A list comprehension provides a compact way of mapping a list into another list by applying a function to each of the elements of the list.

Press + to interact
a_list = [1, 9, 8, 4]
print ([elem * 2 for elem in a_list] ) #①
#[2, 18, 16, 8]
print (a_list) #②
#[1, 9, 8, 4]
a_list = [elem * 2 for elem in a_list] #③
print (a_list)
#[2, 18, 16, 8]

① To make sense of this, look at it from right to left. a_list is the list you’re mapping. The Python interpreter loops through a_list one element at a time, temporarily assigning the value of each element to the variable elem. Python then applies the function elem * 2 ...

Access this course and 1400+ top-rated courses and projects.