Lists#
Exercise 1: Explain this error#
my_list = [1, 2, 3, 4]
print(my_list[10])
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[3], line 2
1 my_list = [1, 2, 3, 4]
----> 2 print(my_list[10])
IndexError: list index out of range
Exercise 2: Print the first, the last and second to last item in the list#
Remember that you can use negative indices.
ta = [-0.19,-0.177,-0.308,-0.289,-0.193,-0.057,0.077,0.026,0.029,0.068,0.256, 0.342, 0.591, 0.792]
# your solution here
print(ta[-2])
0.591
Exercise 3: Slice indexing#
Use slice indexing to print
only the odd elements of the list (odd elements are the first, third, fifth etc. elements)
only the even elements of the list (even elements are the second, fourth, sixth etc. elements)
the list elements in reverse order
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# edit this:
print('even:', my_list[1::2])
print('odd:', my_list[::2])
print('reverse:', my_list[::-1])
even: [2, 4, 6, 8]
odd: [1, 3, 5, 7, 9]
reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1]
Exercise 4: Manipulating lists#
Add the item 10
to the end of the list
Bonus: Add the item 0
to the beginning of the list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# your solution here
my_list.append(10)