Lesson 3 ❮ Lesson List ❮ Top Page
❯ 3.1 Tuples
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 7m 4s
☷ Interactive readings 5m
Tuples are used to store multiple items in a single variable. It can be written with round brackets ( ) or simply separating a sequence with commas.
The difference with a list is that the elements of the tuple cannot be changed, added or reordered after the tuple has been created.
Getting/slicing element(s) in a tuple is similar as in a list--write after the tuple [index] with the index number inside. You can also use index() and count() just like in list.
The elements inside the tuple cannot be modified as well.
Due to its unchangeable property, many list methods cannot be applied. However, you can use len(), index() and count() since they are not modifying the tuple.
Generator expression is similar to list comprehension. The resulting object is called a generator.
You cannot print generator directly without converting it to list/tuple first. To convert this into a tuple, you can use tuple().
Use a tuple when you know what information goes in the container that it is. For example, when you want to store a person’s information.
But when you want to store similar elements, you should use a list. You can convert a list to a tuple using tuple().
As previously mentioned, lists and tuples share the methods index() and count(). However, the methods append(), insert(), remove(), pop(), sort(), and reverse() cannot be used in tuples.
The only fix to these 6 errors is to change the tuple into a list--or delete Line 3-11.