Lesson 6
Dealing with Sequences of Objects
Chapter 7: Tuples
Initialising tuples
Creating a new tuple
in Python is just like creating a list
, except that you use (parenthesis) instead of [square brackets].
>>> my_vector = (1, 3, 4)
>>> print(my_vector)
You can also convert an existing list
(or in fact any Python sequence type like range()
) into a new tuple
object.
>>> my_list = [1, 3, 4]
>>> my_vector = tuple(my_list)
>>> print(my_vector)
(1, 3, 4)
A Python quirk! If your tuple has one single element, you should include a comma after the first element to indicate that it is a tuple. Otherwise, Python will treat it as a single variable (the parenthesis will just be a parenthesis). Ugly, I know.
>>> non_tuple = (1)
>>> print(non_tuple)
1
>>> print(type(non_tuple))
<class 'int'>
>>> singleton = (1,)
>>> print(singleton)
(1,)
>>> print(type(singleton))
<class 'tuple'>