Tuples

Tuples are ordered collection of arbitrary objects, immutable, work like lists, and are written within
parentheses.

Examples:

my_tuple = (1, 2, 3)
>>>
#empty tuple
>>> empty_tuple = ()
>>> empty_tuple
()
>>>
#one item tuple
>>> one_item_tuple = (4,)
>>> one_item_tuple
(4,)
>>>
#four item tuple
>>> four_item_tuple = (0, 1.5, 'Dan', 99)
>>> four_item_tuple
(0, 1.5, 'Dan', 99)
>>>
#four item tuple with no parentheses
>>> four_item_tuple_no_parentheses = 0, 1.5, 'Dan', 99
>>> four_item_tuple_no_parentheses
(0, 1.5, 'Dan', 99)
>>>
#nested tuple
>>> nested_tuple = (1, 2, ('Dan', 4))
>>> nested_tuple
(1, 2, ('Dan', 4))

Concatenation

>>> my_tuple = (1, 2, 3)
>>> my_tuple + (8, 9)
(1, 2, 3, 8, 9)

Repetition

>>> my_tuple * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)<

Indexing

>>> my_tuple[2]
3

Slicing

>>> my_tuple[1:3]
(2, 3)

Slicing, indexing

>>> my_tuple[0], my_tuple[1:3]
(1, (2, 3))

>The len() function

>>> len(my_tuple)
3

Comma and parentheses

Parentheses also enclose expressions so, you need to tell Python when a single object in parentheses is a tuple object.
If you want a single-item tuple then add a trailing comma after the item.

>>> T = (5)
>>> T
5
>>> Tu = (5,)
>>> Tu
(5,)

Sorting a tuple

>>> my_tuple_1 = (1, 8, 77, 16, 6)
>>> list_from_tuple = sorted(my_tuple_1)
>>> list_from_tuple
[1, 6, 8, 16, 77]
>>> sorted_tuple = tuple(list_from_tuple)
>>> sorted_tuple
(1, 6, 8, 16, 77)

Covert tuples with list comprehension

>>> T = (1, 2, 3, 4)
>>> L = [x + 5 for x in T]
>>> L
[6, 7, 8, 9]

The index() and count() methods of tuples

>>> my_tuple_2 = (1, 2, 5, 9, 2, 3, 1, 5, 2, 1, 9, 3, 2, 1)
>>>
#the index of number 2
>>> my_tuple_2.index(2)
1
>>>
#first 2 after the index 2 (it is on index 4)
>>> my_tuple_2.index(2, 2)
4
>>>
#first 2 after index 5, (it is on index 8)
>>> my_tuple_2.index(2, 5)
8
>>>
#how many 2(s) are there
>>> my_tuple_2.count(2)
4

Leave a Reply