06_tuples
06_tuples
Tuples
A tuple is a collection of different data types which is ordered and unchangeable (immutable). Tuples
are written with round brackets, (). Once a tuple is created, we cannot change its values. We cannot
use add, insert, remove methods in a tuple because it is not modifiable (mutable). Unlike list, tuple has
few methods. Methods related to tuples:
Creating a Tuple
Empty tuple: Creating an empty tuple
# syntax
empty_tuple = ()
# or using the tuple constructor
empty_tuple = tuple()
# syntax
tpl = ('item1', 'item2','item3')
Tuple length
We use the len() method to get the length of a tuple.
# syntax
tpl = ('item1', 'item2', 'item3')
len(tpl)
# Syntax
tpl = ('item1', 'item2', 'item3')
first_item = tpl[0]
second_item = tpl[1]
Negative indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second
last and the negative of the list/tuple length refers to the first item.
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
first_item = tpl[-4]
second_item = tpl[-3]
fruits = ('banana', 'orange', 'mango', 'lemon')
first_fruit = fruits[-4]
second_fruit = fruits[-3]
last_fruit = fruits[-1]
Slicing tuples
We can slice out a sub-tuple by specifying a range of indexes where to start and where to end in the
tuple, the return value will be a new tuple with the specified items.
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
all_items = tpl[0:4] # all items
all_items = tpl[0:] # all items
middle_two_items = tpl[1:3] # does not include item at index 3
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
all_items = tpl[-4:] # all items
middle_two_items = tpl[-3:-1] # does not include item at index 3 (-1)
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
'item2' in tpl # True
Joining Tuples
We can join two or more tuples using + operator
# syntax
tpl1 = ('item1', 'item2', 'item3')
tpl2 = ('item4', 'item5','item6')
tpl3 = tpl1 + tpl2
# syntax
tpl1 = ('item1', 'item2', 'item3')
del tpl1