List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Example: You want to create a list of all the fruits that has the letter "a" in the name.
Without list comprehension you will have to write a for
statement with a conditional test inside:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Try it Yourself »With list comprehension you can do all that with only one line of code:
Examplefruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Try it Yourself »The list comprehension is wrapped around square backets, contains one or more for
statements, zero or more if
statements, and returns a new list.
Track your progress - it's free!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4