Ensure that you are familiar with the lesson 11 and the text (ch10) for tuples and also with the sections on strings and lists. If you are familiar with these, tuples are easy.
The tuple object in python is a collection that can store different object types. Indexing and iteration through a tuple works exactly the same as with strings and lists.
Lists are an IMMUTABLE data structure.
You can see that tuples are very much like a list that cannot be changed, and use the round braces/brackets. Because they are immutable (unchangeable) there are much fewer methods associated with tuples than with lists, or even with strings. Strings are also immutable, but contain a specific type, whereas tuples can contain many types of objects. We might typically use tuples to define RGB colours, since they do not change e.g. RED is (255, 0 , 0).
Other collections can be converted to a tuple using the builtin function tuple(). Many of the usual functions and methods that are also implemented for strings and lists will seem familiar- but remember that these methods are implemented differently under the hood for tuples- methods are NOT shared between classes.
Here are some examples of common functions and methods you might use, or try to use.
>>> my_list = [1, 2.4, "Jimmy"]
>>> tuple(my_list) # convert list to tup
(1, 2.4, 'Jimmy')
>>> word = 'hello'
>>> tuple(word) # convert str to tup
('h', 'e', 'l', 'l', 'o')
>>> t1 = (1, 2, 3, 4, 5) # instantiate a tuple
>>> t2 = (2, 4, 4, 6, 8) # instantiate another tuple
# common functions
>>> len(t1) # get the number of elements in the tuple
5
>>> max(t2) # find the highest value inside the tuple
8
>>> min(t2) # find the lowest value inside the tuple
2
# methods and indexing
>>> t2.count(4) # fins the number of instances of (obj w/value) inside the tuple
2
>>> t2[-1] # use indexing
8
>>> t1[2] = 7 # tuples are immutable
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t2.index(6) # find the index of the value inside the tuple
3
>>> t2.index(3) # trying to get the index of something not there causes an error
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
>>> # this could be handled by first checking if obj is in the tuple
>>> # You may use the in keyword with tuples
>>> t1.append(9) # tuples are immutable
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> t1 = t1 + t2 # tuples are immutable, but this just creates a new one and overwrites the object that t1 is pointing to.
>>> t1
(1, 2, 3, 4, 5, 2, 4, 4, 6, 8)
>>> t1.sort() # tuples are immutable
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'