Exercises
Contents
5.4. Exercises#
5.4.1. Exercise 1#
Suppose that we have the following list of numbers: list_of_numbers = [1,2,3]
. Then we want to insert a list of numbers at position 1. For this we execute: list_of_numbers.insert(1, [30,40])
. Do you think this is valid? Will this code produce any errors? What will happen after executing it? You can use the cell below to check your answer.
# write your code here
5.4.2. Exercise 2#
Suppose that someone has given us the following list of wrongly mixed fermented food and drinks: fermented_food = ['milk', 'yoghurt', 'beer', 'cider', 'tempeh', 'sauerkraut', 'kefir']
. Our task is to have the food in one list and the drinks in another one. Find a way to separate them by using list comprehension.
# write your code here
5.4.3. Exercise 3#
You are given the following list of numbers: [10,20,24,45,30,10,32,20,14,8,9,12,24,20,12,3]
.
Write a function to find the first and last indices of a given key value (passed as argument) in a list.
Hint: use loops and your own variables.
# write function here
# write function calls here
5.4.4. Exercise 4#
You are given the following list of numbers: [10,20,24,45,30,10,32,20,14,8,9,12,24,20,12,3]
.
Write a function to find the first and last indices of a given key value (passed as argument) in a list this time using the index()
method. Hint: Function definition may look something like: def find_key_2(key, list)
. Also the function should return a tuple containing the first and last indices.
# write function here
# write code here
5.4.5. Exercise 5#
Variables a
and b
mistakenly were assigned values a = 3
and b = 5
. The correct version would be: a = 5
and b = 3
. Use sequence unpacking to correct this.
# write your code here
5.4.6. Exercise 6#
What happens when you make a shallow copy of a tuple and then change one of the tuples? Where will the changes be reflected?
# write answer here - you can write code to test your reasoning as well
5.4.7. Exercise 7 (Optional)#
You are given a list of values: [1,2,3,4,5,6,7,8,9]
and need to find which of the squares of any of the values are divisible by 2. Use a lambda expression to find out. Hint: the iterable of the map()
function has to be used as input to the filter()
function.
# write your code here