Sequence types - Exercises
Time for you to practice again. Here are some exercises on selecting from lists and tuples
Many thanks to the following people for contributing to these exercises: Joe Stacey, Oana Cocarascu, Josiah Wang
Ex1: Create the following collections using a literal:
- An empty tuple
- A tuple containing exactly one item
- A tuple containing three integers
- A list containing three strings
- A list with two tuples, first tuple with two elements and the second tuple with one element
- A list containing an integer, a string, and a tuple
Ex2: Given the following code…:
x = ["a", "b", "c"]
y = [x] * 3
… change the value of y[0][0] and see what changes. Why is this change happening?
Ex3: Given s = ‘foobar’, try to understand what the following commands do:
s[::2]
s[::-1][-1]
s[len(s)-1]
s[0] + s[-1]
s[::-2]
s[::-1]
Ex4: Write the slice expression that gives every third element of the list my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8], starting with the last element and proceeding backwards to the first
Ex5: Write a line of code that returns the 1st and 3rd element of a list. For example with my_list = [1, 2, 3, 4, 5] this would return [1, 3]
Challenge question:
Ex6: Given a list of non-empty tuples, write a program to return a list sorted in reverse order by the sum of the elements in each tuple:
For example, for my_list = [(1, 7), (1, 3), (3, 4, 5), (1, 1, 1), (2, 2)]
the output would be: [(3, 4, 5), (1, 7), (1, 3), (2, 2), (1, 1, 1)]
Hint: you may want to consider zip(list_A, list_B)
which creates a tuple of two lists