# Python List Comprehension Practice Exercises and Problems

1 Consider the following list and dictionary in your code:

```a_list = list(range(1, 11))
a_dictionary = {
1 : 'one',
2 : 'two',
3 : 'three',
4 : 'four',
5 : 'five',
6 : 'six',
7 : 'seven',
8 : 'eight',
9 : 'nine',
10 : 'ten'}```

(a) Use a list comprehension that iterates over a_list, prints a list composed of each value in a_list multiplied by 10.

The desired list must be like this:

`[ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 ]`

Code

`[i*10 for i in a_list]`

(b) Use a list comprehension that iterates over a_list, prints a list composed of odd numbers from 1 to 9.

The desired list must be like this:

`[ 1, 3, 5, 7, 9 ]`

Code

`[i for i in a_list if i%2!=0]`

(c) Using a list comprehension which iterates over a_list and whose output expression accesses a value from a dictionary, print a list composed of the text form of each even number from 2 to 10, e.g.,

`[ 'two', 'four', 'six', 'eight', 'ten' ]`

Code

`[a_dictionary[i] for i in a_list if i%2==0]`

(d) Write a function named odd_or_zero which takes one parameter, a number, and returns that number if it is odd or returns 0 if the number is even. Then using a list comprehension which iterates over a_list and calls your odd or zero function for each value, print a list like the following:

`[ 1, 0, 3, 0, 5, 0, 7, 0, 9, 0 ]`

Code

```def odd_or_zero(num):
if num%2==0:
return 0
else:
return num
[odd_or_zero(i) for i in a_list]```

(e) Prompt the user for a number, which will be returned from input as a string data type. Strings can be iterated over like lists, such that the loop repeats for each character in the string. Using a list comprehension which iterates over the user-entered string and whose output expression accesses values from a_dictionary, print a list of the text form of each digit from the user-entered string, e.g.,

```Enter a number: 195
[ 'one', 'nine', 'five' ]```

Code

```string = input('Enter a number: ')
[a_dictionary[int(number)] for number in string]```

(f) Using the same user-entered number and list comprehension as above, also print the text form of the digits in a single string (using the string join function) with a dash between each text form of the digit, e.g.,

`one-nine-five`

Code

```string = input('Enter a number: ')
lst = [a_dictionary[int(number)] for number in string]
'-'.join(lst)```

2 Using list comprehension, square each element of a list.

Input

`list_a = [5,5,2,10,1,6]`

Output

`list_b = [25,25,4,100,1,36]`
```list_a = [5,5,2,10,1,6]
list_b = [a*a for a in list_a]
print(list_b)```

3 Write a list comprehension that builds a list containing only the names with at least 8 characters.

Input

`avengers = ["Iron Man", "Captain America", "Thor", "The Incredible Hulk", "Bla avengers ck Widow", "Hawkeye"]`

Code

`[avenger for avenger in avengers if len(avenger)>=8]`

4 Write a list comprehension that builds a list containing only even numbers over 100.

Input

`numbers = list (range (50,150,5))`

Code

`[number for number in numbers if number%2==0 and number>100]`

5 Add % in front and end of every single word in a given string str: "Fall is Awesome in Alabama" only using list comprehensions.

Desired Output

`['%Fall%','%is%','%Awesome%','%in%','%Alabama%']`

Code

```str = "Fall is Awesome in Alabama"
['%'+word+'%' for word in str.split()]```

6 Use list comprehension to create a myList which consists of the positive integers 1-100.

```myList = [i for i in range(1, 101)]
print(myList)```

7 Use list comprehension to create myListEvens which consists of all entries in myList that are even.

```myList = [i for i in range(1, 101)]
myListEvens = [number for number in myList if number%2==0]
myListEvens```

8 Use list comprehension to create a list of cubes of the integers 1-5.

`[i**3 for i in range(1,6)]`

9 Use list comprehension to make a list of the first letter of each word in the following list:

`wordList = ["this", "is", "an", "example"]`

Code

```wordList = ["this", "is", "an", "example"]
[word for word in wordList]```

10 Write a list comprehension that returns a list [0, 1, 4, 9, 16, ...., 625] starting from range(0, 26).

`[number*number for number in range(0, 26)]`

11 Write a list comprehension that returns the list ["1**2=1", "2**2=4", "3**2=9", ...., "25**2=625"]

`[str(number) + "**2=" + str(number*number) for number in range(1, 26)]`

12 A string is given:

`msg = "happy birthday!"`

Write a list comprehension that prints a list ['h', 'a', 'p', 'p', 'y', 'b', 'i', 'r', 't', 'h', 'd', 'a', 'y']

Do not print out the space or the !.

```msg = "happy birthday!"
[m for m in msg if m!=" " and m!="!"]```

13 Consider a list of strings, like this: ['one', 'seven', 'three', 'two', 'ten']. Write a list comprehension that produces a list with tuples where the first element of the tuple is the length of an element in the initial list. The second element of the tuple is the element of the initial list capitalized. The resulting list contains only tuples for strings with a length longer than three characters.

For our example above, the list comprehension should return [(5, 'SEVEN'), (5, 'THREE')].

```string = ['one', 'seven', 'three', 'two', 'ten']
[(len(str), str.upper()) for str in string if len(str)>3]```

14 Consider a list of full names formatted "Firstname Lastname", like ["Jules Verne", "Alexandre Dumas", "Maurice Druon"].

Write a list comprehension that produces a list with the full names in the format "Lastname, Firstname". The resulting list should look like

`['Verne, Jules', 'Dumas, Alexandre', 'Druon, Maurice']`
```names = ["Jules Verne", "Alexandre Dumas", "Maurice Druon"]
[name.split() + ", " + name.split() for name in names]```

15 Using list comprehension, write a Python program to print the list after removing the 0th, 2nd, 4th, and 6th numbers in [12,24,35,70,88,120,155].

```lst = [12,24,35,70,88,120,155]
[value for index,value in enumerate(lst) if index!=0 and index!=2 and index!=4 and index!=6]```

16 A list of lists is given:

```prairie_pirates = [
['Tractor Jack', 1000, True],
['Plowshare Pete', 950, False],
['Prairie Lily', 245, True],
['Red River Rosie', 350, True],
['Assiniboine Sally', 620, True],
['Thresher Tom', 150, True],
['Cranky Canola Carl', 499, False]
]```

Each sublist contains three pieces of information on one famous prairie pirate- their pirate name (pirates can have secret identities too!), the number of sacks of assorted grains they have plundered from unsuspecting farmers in the last year, and a Boolean value indicating whether they like parrots.

(a) Use a single list comprehension to create a list of the pirate names who plundered more than 400 sacks of assorted grains.

```best_plunderers = [pirate for pirate in prairie_pirates if pirate>400]
print(best_plunderers)```

(b) Use a single list comprehension to create a list of the pirate names who don't like parrots.

```parrot_haters = [pirate for pirate in prairie_pirates if pirate==False]
print(parrot_haters)```

(c) Suppose that the average market value of a sack of grain is \$42. Use a single list comprehension to create a list of the market values of each pirate's grain.

```plunder_values = [pirate*42 for pirate in prairie_pirates]
plunder_values```

(d) Use a single list comprehension to create a list of lists where each sublist consists of a pirate's name and the value of his/her plundered sacks of grain (calculate grain values as in part (c)), but only include those pirates who like parrots.

```names_and_plunder_values = [[pirate, pirate*42] for pirate in prairie_pirates if pirate==True]
print(names_and_plunder_values)```

17 A list of lists is given:

```SPL_Patrons = [
['Kim Tremblay', 134, True],
['Emily Wilson', 42, False],
['Jessica Smith', 215, True],
['Alex Roy', 151, True],
['Sarah Khan', 105, False],
['Samuel Lee', 220, True],
['William Brown', 24, False],
['Ayesha Qureshi', 199, True],
['David Martin', 56, True],
['Ajeet Patel',69, False]
]```

Each sublist contains three pieces of information about the library patrons at Saskatoon Public Library (SPL) - patron's name, the number of books they have borrowed throughout the last year, and a Boolean value indicating whether they are under 20.

(a) Use a single list comprehension to create a list of the patron names who borrowed more than 100 books last year.

```good_readers = [patron for patron in SPL_Patrons if patron>100]

(b) Use a single list comprehension to create a list of the patron names who are not under 20.

```not_teenagers = [patron for patron in SPL_Patrons if patron==False]
print(not_teenagers)```

(c) Suppose that a patron saves on average \$11.95 by borrowing a book instead of buying it. Use a single list comprehension to create a list of the amount saved for each patron.

```saved_amount = [patron*11.95 for patron in SPL_Patrons]
print(saved_amount)```

(d) Use a single list comprehension to create a list of lists where each sublist consists of a patron's name and the total amount he/she saved last year as in part (c)), but only include those patrons who are under 20.

```names_and_saved_amount = [[patron, patron*11.95] for patron in SPL_Patrons if patron==True]
print(names_and_plunder_values)```