< Prev
Next >

# Python - Tuple

Today we are going to understand one of Python's most important collection data type - tuple. A tuple is an ordered sequence of items. The items of a tuple are arranged in the order in which they are declared in a tuple, where the first item is stored at an index zero, the second item at index one and so on.

• ## Important properties of tuple

• A tuple is immutable i.e. existing items cannot be modified and we cannot insert new items to it.
• We can store duplicate values in a tuple.
• Each item in a tuple is accessible through its index.

• ## How to create a tuple in Python?

• In order to create a tuple with items, we must declare its items within a pair of parenthesis ( ), where each item is separated by a comma(,) operator. Let us show you a simple example of how to create a tuple with items.

``````#Python - Creating a tuple with items

customer =('Edward', 27, 178.5, 'M')
print(customer)

``````

## Output

``('Edward', 27, 178.5, 'M')``

In the example above, we have created a tuple named customer, containing 4 items separated by the comma(,) operator and all items are enclosed within a pair of parenthesis ( ). The items of tuple are displayed in the order in which they were declared within a tuple.

• ## Extracting each item of a tuple

• Items of a tuple are stored using zero-based indexing i.e. the first item of a tuple is stored at an index zero , second element at index one and so on.

``````#Python - Extracting each time of a tuple using its index.

misc =(2 ,-19, 17.5, 'have a good day!')
print(misc)
print(misc)
print(misc)
print(misc)
print(misc)``````

## Output

``````(2, -19, 17.5, 'have a good day!')
2
-19
17.5
have a good day!``````

In the example above, we have created a tuple named misc, containing 4 items separated by the comma , and enclosed within a pair of parenthesis ( ).
We have accessed each item of a tuple by accessing its index position :
• The first tuple element 2 is accessed using its index position 0
• The second tuple element -19 is accessed using its index position 1
• The third tuple element 17.5 is accessed using its index position 2
• The fourth tuple element have a good day is accessed using its index position 3

• ## Iterating over items in a tuple using for loop

• Using the membership operator in with the for loop, allows us to iterate over items in a tuple. Let us see how we do this.

``````#Python - Iterating over items in a tuple using for loop

# Creating a tuple
misc =(2 ,-19, 17.5, 'have a good day!')

# Using for loop to iterate over items in a tuple
for val in misc:
print(val)``````

## Output

``````2
-19
17.5
have a good day!``````

• ## A tuple is immutable

• Once we have declared a tuple with its items, it is immutable i.e. its existing items cannot be modified and we cannot insert or append new items to it. Let us prove this by an example.

``````#Python - Tuple once declared in immutable

misc2 =(2 ,-19, 17.5, 'have a good day!')

#Trying to insert a new item at index 1 in a tuple - Invalid!
misc2= 5``````

## Output

``````Traceback (most recent call last):
File "D:/Python Programs/tuple3.py", line 6, in <module>
misc2= 5
TypeError: 'tuple' object does not support item assignment``````

In the example above, we have created a tuple named misc2 with 4 items and we have tried to insert a new item at its index 1, which as we said has raised a compile error, saying that a tuple does not support individual item assignment by using its index position, which also says that we can only create a tuple with its elements, while declaring it.

• ## Methods of tuple

• Now let us discuss two important methods of tuple collection data type - index() and count().

Methods Description
index() To find the index of an item in a tuple.
count() To find the number of times an item exists in a tuple.

• ## To find the index of an item in a tuple - index() method

• We can use index() method of tuple data type, to find the first index of an item within a tuple. This method takes an item(whose index is to be searched) as an argument and returns its first index(if found) or else, it reports a ValueError if the searched item is not found in a tuple.

``````#Python - Using index() method  of a tuple data type

misc =(2 ,-19, 17.5, 'have a good day!', 17.5)
print('First index of item 17.5 : ', misc.index(17.5)))``````

## Output

``First index of item 17.5 : 2``

The above program finds the first index of item 17.5, which exists twice within the searched tuple but the method index returns only the first index of the searched item.

• ## To find the number of times an item exists in a tuple - count() method

• We can store duplicate items in a tuple and this raises a question - if we can find the number of times a specific item exists in a tuple? The answer is, yes!

The tuple data type gives us another important method count, using which we find the total number of times an item exists in a tuple. This method takes the value of an item(to be searched) as its argument and returns the total number of times it is contained in a tuple.

``````#Python - Using the count() method with a tuple

misc =(5 , 'have a good day!', 5)
print('Total number of times item 5 is contained in a tuple : ', misc.count(5))``````

## Output

``Total number of times item 5 is contained in a tuple : 2``

• ## To find the total number of items in a tuple

• We can use the len() function to find the total number of items in a tuple. This function takes a tuple as an argument and returns the total number of items it contains.

``````#Python - Using len() function with a tuple

misc =(2 ,-19, 17.5, 'have a good day!')
print('Total number of elements in tuple : ', len(misc))``````

## Output

``Total number of elements in tuple : 4``

• ## Concatenating tuples using the arithmetic + operator

We could even create a new tuple by concatenating different tuples using the arithmetic + operator. The arithmetic + operator is overloaded to add integers, floating values, concatenate string values and concatenate tuples.

``````#Python - Concatenating tuples using the arithmetic + operator

#First tuple
tup1 =('A', -20)

#Second tuple
tup2 =('have a good day', 2019)

#Printing tuples
print('Tuple1 : ', tup1)
print('Tuple2 : ', tup2)

#Creating a new tuple by concatenating existing tuples
tup3 = tup1 + tup2

#Printing new tuple
print('Tuple3 : ',tup3)``````

## Output

``````Tuple1 :  ('A', -20)
Tuple2 :  ('have a good day', 2019)
Tuple3 :  ('A', -20, 'have a good day', 2019)``````

In the program just above, we have created two tuples and have then created a third one by concatenating the first two tuples by using the arithmetic + operator.

• ## Some important built-in functions to work with tuple

• Functions Description
max() Returns the maximum value in a tuple.
min() Returns the minimum value in a tuple.
len() Returs the total length of a tuple.
sum() Returns sum of all elements in a tuple.
sorted() Returns a sorted copy of a tuple.
any() Returns true if any element in a tuple is true, else false.
all() Returns true if all elements in a tuple are true, else false.

``````#Python - Functions working with tuples

#First tuple
tup1 =(19, -20, 209, 799.99, -15.4)

#Second tuple
tup2 =(1, True, False, 0) # 1 is boolean true, 0  for boolean false
# True(with capital T) is boolean true, False(with capital F) is boolean false

#Printing tuples
print('Tuple1 : ', tup1)
print('Tuple2 : ', tup2)

#Using max() function with a tuple.
print('Maximum value in Tuple1 : ', max(tup1))

#Using min() function with a tuple.
print('Minimum value in Tuple1 : ', min(tup1))

#Using sum() function with a tuple.
print('Sum of values in Tuple1 : ', sum(tup1))

#Using sorted() function with a tuple.
print('Sorted copy of Tuple1 : ', sorted(tup1))

#Using all() function with a tuple.
print('all() boolean true values in Tuple2 : ', all(tup2))

#Using any() function with a tuple.
print('any boolean true value in Tuple2 : ', any(tup2))``````

## Output

``````Tuple1 :  (19, -20, 209, 799.99, -15.4)
Tuple2 :  (1, True, False, 0)
Maximum value in Tuple1 :  799.99
Minimum value in Tuple1 :  -20
Sum of values in Tuple1 :  992.59
Sorted copy of Tuple1 :  [-20, -15.4, 19, 209, 799.99]
all() boolean true values in Tuple2 :  False
any boolean true value in Tuple2 :  True``````

< Prev
Next >
< Python global variables
Python List >   