List comprehension gives us the ability to create lists from existing lists in an elegant manner.
Examples
numbersList = [2, 4, 6, 8] # A list
double_numbers_list = [n*2 for n in numbersList] # [4, 8, 12, 16] using list comprehension
As we can see we were able to double the numbers in numbersList
list by 2 in a much more elegant way than if we did it the following way:
double_numbers_list = []
for n in numbersList:
double_numbers_list.append(n*2)
or even using map
with a lambda
function:
numbersList = [2, 4, 6, 8]
double_numbers_list = list(map(lambda n : n*2, numbersList))