Let’s check out some exercises that will help understand List Comprehension better.

Exercise 16-a

Create an identical list from the first list using list comprehension.


You can type your list comprehension inside brackets: []

lst2 = [i for i in lst1]

Exercise 16-b

Create a list from the elements of a range from 1200 to 2000 with steps of 130, using list comprehension.


You can type your list comprehension inside brackets: []

range can be constructed by using 3 parameters:
range(start,stop,step)

rng = range(1200, 2000, 130)
lst = [i for i in rng]

Exercise 16-c

Use list comprehension to contruct a new list but add 6 to each item.


You can type your list comprehension inside brackets: []

You can start your list comprehension with [i+6 for i…]

lst2 = [i+6 for i in lst1]

 

Exercise 16-d

Using list comprehension, construct a list from the squares of each element in the list.


You can type your list comprehension inside brackets: []

i**2  is the correct syntax to get the square of a number in Python.

lst2 = [i**2 for i in lst1]

 

Exercise 16-e

Using list comprehension, construct a list from the squares of each element in the list, if the square is greater than 50.


You can type your list comprehension inside brackets: []

i**2  is the correct syntax to get the square of a number in Python.

lst2 = [i**2 for i in lst1 if i**2>50]

 

Exercise 16-f

Given dictionary is consisted of vehicles and their weights in kilograms. Contruct a list of the names of vehicles with weight below 5000 kilograms. In the same list comprehension make the key names all upper case.


You can type your list comprehension inside brackets: []

[i.upper() for i…] can be a good start for the comprehension.

dict[i]  can be used to access the value of the key: i in a dictionary named dict

lst = [i.upper() for i in dict if dict[i]<5000]