Mark As Completed Discussion

List Comprehensions

A list comprehension has the same functionality as dict comprehensions, but is for lists. A list has a specific index for each value. For example, look at the following list of flowers:

PYTHON
1flowers = ["Tulip", "Jasmine", "Rose", "Lili", "Daisy"]

If you wanted to create a new list that contains new flowers, you could use a comprehension instead of a loop. The list comprehension has the following syntax:

PYTHON
1list_name = [expression for variable in old_list condition]

Let's create a new list using the flowers one:

PYTHON
1new_flowers = ["new" + flower for flower in flowers]

The output will be a new list as follows:

PYTHON
1["newTulip", "newJasmine", "newRose", "newLili", "newDaisy"]
PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment