List comprehensions
Solve the following exercises with list comprehensions.
Exercise 1
['car', 'tram', 'metro']
→ ['CAR!', 'TRAM!', 'METRO!']
Exercise 2
['mario', 'luigi', 'peach']
→ ['Mario', 'Luigi', 'Peach']
Exercise 3
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, that is initialize a list with ten 0s
Exercise 4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
→ [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Exercise 5
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
→ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(notice that there are strings in the first list)
Exercise 6
"1234567"
→ [1, 2, 3, 4, 5, 6, 7]
, that is we have a number as a string and we want to put its digits to a list (as numbers)
Exercise 7
'The quick brown fox jumps over the lazy dog'
→ [3, 5, 5, 3, 5, 4, 3, 4, 3]
, that is store the length of each word
Exercise 8
"python is an awesome language"
→ ['p', 'i', 'a', 'a', 'l']
, that is collect the first character of every word in a list
Exercise 9
'The quick brown fox jumps over the lazy dog'
→ [('The', 3), ('quick', 5), ('brown', 5), ('fox', 3), ('jumps', 5), ('over', 4), ('the', 3), ('lazy', 4), ('dog', 3)]
, that is create a list of tuples, where a tuple consists of two parts: (word, length_of_word).
Exercise 10
[0, 2, 4, 6, 8]
, that is store even numbers less than 10 in a list (including 0 too)
Exercise 11
Take the whole numbers less than 20 and calculate their squares. Keep only the even square numbers ([0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
).
Exercise 12
Take the whole numbers less than 20 and calculate their squares. Keep only those square numbers whose last digit is "4" ([4, 64, 144, 324]
).
Exercise 13
Collect the upper case letters of the English alphabet in a list (use the chr
function), and then concatenate the elements to form one string: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.
Exercise 14
[' apple ', ' banana ', ' kiwi']
→ ['apple', 'banana', 'kiwi']
, that is remove whitespaces from both sides of each word
Exercise 15
[1, 0, 1, 1, 0, 1, 0, 0]
→ "10110100"
, that is concatenate the digits in the list to form a string