List comprehension

Python offers a compact method called "list comprehension" to create lists from lists. Consider the following case of a list that is processed to create another list:

In [ ]:
iterable=range(5)
my_list=[]

for x in iterable:
    if x<=3:
        my_list.append(x**2)

print (my_list)

Using list comprehension this can be done using the following line:

In [ ]:
my_list=[x**2 for x in iterable if x<=3]

print (my_list)

You can see that a loop such as

for item in iterable:
    if conditional:
        expression

is equivalent to

[expression for item in iterable if conditional]


You are always creating a list with list comprehension. If you don't necessarily want a list, a loop can be the simpler option.

Exercise 1:

Use list comprehension to translate the sentence list

diogenes=['Cede','paulum','e','sole']

using the dictionary

dic={'Cede':'Go','paulum':'a little','e':'out of','sole':'the sun'}

into an answer sentence list.

In [ ]:
# your solution here

Exercise 2:

Use list comprehension to determine a list with all numbers between 1 and 1000 for which the digit sum is equal to 7.

In [ ]:
# your solution here