A tuple is a Data Structure in the Python programming language. It is used to store the sequence of Python objects. In other words, we can say that a Tuple is a collection of Python objects.
How to create a Tuple in Python?
There are two ways of creating or defining tuples in python.
First, we can simply assign some comma separated values to a variable. Python will automatically consider it as a tuple. For example,
tup = 1, 2, 3
print(tup)
print(type(tup))
Output:
(1, 2, 3)
<class 'tuple'>
Second, we can write comma separated values inside a bracket which tells python that we are defining a tuple. For example,
mytup = (4, 5, 'a')
print(mytup)
print(type(mytup))
Output:
(4, 5, 'a')
<class 'tuple'>
We have seen two ways to define a tuple but defining a tuple with single element is slightly different. To define a tuple with single element we either need to explicitly tell python that we want a tuple with single element which is done using the tuple() constructor as follows.
a = tuple('a')
print(a)
print(type(a))
Output:
('a',)
<class 'tuple'>
Or we can also specify that item inside parenthesis followed by a comma but if the element is not followed by a comma, python will not consider it as a tuple but an object. For example,
onetuple = ('abs')
print(onetuple)
print(type(onetuple))
mytuple = ('abs',)
print(mytuple)
print(type(mytuple))
Output:
abs
<class 'str'>
('abs',)
<class 'tuple'>
How to find Tuple length in python?
Length of a tuple is equal to the number of objects present in it. We can determine length of a tuple using the len() function as follows.
tup = ('x', 'y', 1, 2, 3)
print(tup)
print(len(tup))
Output:
('x', 'y', 1, 2, 3)
5
What is Indexing in python tuple?
Elements inside a tuple are in order. Therefore, it can store duplicate values. We can distinguish between two duplicate objects using their position. Indexing is a way to access one or more elements from the tuple . The first object inside the tuple have 1st position. But index of starting element is [0]. Similarly index of second element will be [1], for third element its [2] and so on.
So, we can say that index of elements inside the tuple starts from 0 and goes till length of tuple – 1. We can access elements inside a tuple using index [ ] operator. Value inside the square parenthesis determines the index of element we need to access. For example,
tup = ('a', 'b', 'c', 'd', 'e')
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[3])
print(tup[4])
Output:
a
b
c
d
e
Python also supports negative indexing. In negative indexing element is accessed from the end. Therefore, Index of last element is -1, second last element is -2 and so on. For example,
tup = ('a', 'b', 'c', 'd', 'e')
print(tup[-1])
print(tup[-2])
print(tup[-3])
print(tup[-4])
print(tup[-5])
Output:
e
d
c
b
a
What is Slicing in tuple in python?
Slicing in Python is similar to slicing in real life that is cutting into slices. Any collection of objects can be sliced to give a smaller collection. Slicing of tuple enables us to get a specific part of a tuple. We can do Slicing using the enhanced version of index operator or square parenthesis [ ] which takes three values each separated by a colon (:).
Syntax – tuple[start : end : step]
mytuple = (11, 22, 33, 44, 55, 66)
#slicing from element at index 1 till end
print(mytuple[1:])
#slicing from element at index 2 to index 4
print(mytuple[2:5])
#slicing from first element to element at index 2
print(mytuple[:3])
#slicing from at index -3 to last element
print(mytuple[-3:-1])
#slicing from element at index 1 to index 5 by step of 2
print(mytuple[1:5:2])
Output:
(22, 33, 44, 55, 66)
(33, 44, 55)
(11, 22, 33)
(44, 55)
(22, 44)
Properties of Python Tuple
Immutability
Tuples are immutable. That means tuples are unchangeable. Once we define a tuple we cannot modify it as well as no element of the tuple can be modified. This is the significant property of tuple that differentiates it from a similar Data Structure List in python.
Therefore, if we try to modify a tuple it will throw an error. However, we can concatenate a tuple with another tuple to give a new tuple. For example,
mytuple = (1, 2, 'xyz', '7')
print(mytuple)
try:
mytuple[2] = 'abc'
except Exception as e:
print(e)
#this statement will not modify mytuple
#but will create a new tuple with same name
mytuple = mytuple + ('pqr', 6)
print(mytuple)
Output:
(1, 2, 'xyz', '7')
'tuple' object does not support item assignment
(1, 2, 'xyz', '7', 'pqr', 6)
Ordered Sequence
As we know, elements inside a tuple are in order. Therefore, the sequence in which a tuple is defined remains the same and all the elements have fixed index.
Duplicates
Tuple supports duplicate entries. That means multiple copy of same object can be present inside a tuple. We can distinguish each similar object based on their index. For example,
tup = (1, 2, 3, 2, 4)
print(tup[1])
print(tup[3])
Output:
2
2
Data type of tuple items
A tuple can consist of different objects where datatype of each object may be different. For example,
tup1 = (1, 2, 3, 4, 5)
tup2 = ('a', '2', 'f')
tup3 = (1, 3, 'abc', True, '9')
print(type(tup1))
print(tup1)
print(type(tup2))
print(tup2)
print(type(tup3))
print(tup3)
Output:
<class 'tuple'>
(1, 2, 3, 4, 5)
<class 'tuple'>
('a', '2', 'f')
<class 'tuple'>
(1, 3, 'abc', True, '9')
What operations can be done on python tuples?
Now we’ll see some of the operations we can perform with the tuples.
A. Concatenation
Concatenation (+) operator concatenates the two tuples into a single sequence. So, two tuples that need to be concatenated are connected by (+) operator.
tup1 = (1, 2, 3, 4)
tup2 = (5, 6, 'a', 'b')
tup = tup1 + tup2
print(type(tup))
print(tup)
Output:
<class 'tuple'>
(1, 2, 3, 4, 5, 6, 'a', 'b')
B. Repetition
Repetition means repeating the same sequence multiple times. It can be done by (*) operator. It is similar to multiplication.
tup = ('a', 'b', 'c')
newtup = tup * 3
print(type(newtup))
print(newtup)
Output:
<class 'tuple'>
('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')
C. Iteration
For iteration we can loop over all the elements of the tuple. We use for loop to iterate over the elements of a tuple.
mytuple = (1, 'b', 5.25, 3, True)
for el in mytuple:
print(type(el))
print(el)
Output:
<class 'int'>
1
<class 'str'>
b
<class 'float'>
5.25
<class 'int'>
3
<class 'bool'>
True
D. Membership
Membership determines whether an element is the member of a tuple. We can determine Membership using membership (in) operator.
tup = (15, 25, 35, 45, 55)
print(15 in tup)
print(20 in tup)
if 15 in tup:
print('15 is a member')
if 20 in tup:
print('20 is a member')
Output:
True
False
15 is a member
What are tuple methods and functions in python?
Python has two built in methods for tuple.
1. count() method
The count() method when invoked on a tuple, takes an element as input and returns the number of occurrences of the specific element in a tuple. If the element does not belong to the tuple,it returns 0.
mytuple = (3, 5, 8, 7, 5, 1, 7, 5)
print(mytuple.count(1237))
print(mytuple.count(5))
print(mytuple.count(1))
Output:
0
3
1
2. index() method
This method searches for a specified element inside the tuple and returns the index of the first occurrence of the element. If the element is not present in tuple it raises the ValueError.
mytup = ('a', 'b', 'c', 'd', 'c')
print(mytup.index('c'))
print(mytup.index('e'))
Output:
2
Traceback (most recent call last):
File "c:\Users\PANDIT\Desktop\Python Programs\Tuple content\tempCodeRunnerFile.py", line 3, in <module>
print(mytup.index('e'))
ValueError: tuple.index(x): x not in tuple
In addition, there are several functions that take tuple as their arguments and returns the respective values.
len(
tup
)
– we have already seen the usage of length function. It simply returns the number of elements present inside the tuple.
del(tup)
– we use this function to delete a tuple. It simply takes the tuple as its argument and deletes it.
tup = (1, 2, 3, 'a')
print(tup)
del(tup)
try:
print(tup)
except Exception as e:
print(e)
Output:
(1, 2, 3, 'a')
name 'tup' is not defined
max(tup)
– this function returns the element having maximum value.
tup1 = (11, 22, 15, 63, 14)
tup2 = ('b', 'a', 'f', 'e')
print(max(tup1))
print(max(tup2))
Output:
63
f
min(tup)
– this function returns the element having minimum value.
tup1 = (11, 22, 15, 63, 14)
tup2 = ('b', 'a', 'f', 'e')
print(min(tup1))
print(min(tup2))
Output:
11
a
tuple(sequence)
– this function converts the specified sequence to a new tuple.
lst = [1, 2, 3, 4]
string = 'python'
lst_tup = tuple(lst)
print(lst_tup)
string_tup = tuple(string)
print(string_tup)
Output:
(1, 2, 3, 4)
('p', 'y', 't', 'h', 'o', 'n')
What is the use of tuple?
We can use Tuples in programming whenever we want to store data in an ordered format. We should only use tuples in the cases where we know that there will be no modifications in the future in our data. However, Tuple gives us the benefit of bundling different objects under a single entity.
Since tuples are immutable iterating through a Tuple is faster and efficient than that of lists. Tuples can also be treated as a dictionary if we have a tuple of two values representing key and value.
Conclusion
In this article, we have read about tuple creation, indexing, slicing, properties of the tuple, operations that can be performed on tuples, methods related to tuples, and the use of tuples. You can read about lists, the mutable version of tuples in this article on python list. You can also read about strings in python in this article about python string.
To read more about python programming, visit https://avidpython.com/.