Skip to content

Python Tuple – An Intro for Beginners

python tuple

Python Tuple is used to store multiple items in a single variable . Python Tuple is surrounded by parentheses (()) . Python provides total 4 built-in data types to store collection of data of which one is Tuple . The other data types are List , Set and Dictionary .

How to create a Tuple in Python ?

There are multiple ways to create a Python Tuple –

  • Using parentheses (())
  • using tuple() function

To check if it is a Tuple or not we can use type() function .

# Creating a tuple in Python

# Using square bracket (())
tuple_from_bracket = ("Rajkumar","apple",True,1,2.5,10)
print(tuple_from_bracket)
# checking the type
print("type of tuple_from_bracket",type(tuple_from_bracket))

# using tuple() function
tuple_from_function = tuple(("Rajkumar","apple",True,1,2.5,10))
print(tuple_from_function)
# checking the type
print("type of tuple_from_function",type(tuple_from_function))
('Rajkumar', 'apple', True, 1, 2.5, 10)
type of tuple_from_bracket <class 'tuple'>
('Rajkumar', 'apple', True, 1, 2.5, 10)
type of tuple_from_function <class 'tuple'>
  • In the above code we have created tuple using various ways
  • First we have created tuple using parentheses (()) . Then we have printed the tuple and also its type .
  • Second we have created tuple using tuple() . Then we have printed the tuple and also its type .
  • From the output we can see that in every case type is tuple .

Note :

Tuple items are separated by comma (,) and it can be of any type as we have seen in the previous code .

How to create a single element Tuple in Python?

To create a single element tuple in Python we need to use comma(,) after the element otherwise Python will not treat it as tuple .

print("type of (1) is =",type((1)))
print("type of (1,) is =",type((1,)))

print("type of ('Rajkumar') is =",type(('Rajkumar')))
print("type of ('Rajkumar',) is =",type(('Rajkumar',)))
type of (1) is = <class 'int'>
type of (1,) is = <class 'tuple'>
type of ('Rajkumar') is = <class 'str'>
type of ('Rajkumar',) is = <class 'tuple'>
  • In the above code when Python see (1) it simply ignores the bracket and treats (1) as 1 . As 1 is a integer so <class 'int'> is printed in the output .
  • But when Python see (1,) due to comma(,) Python can not ignore bracket . So it is treated as tuple .
  • For the same reason type of ('Rajkumar') is printed as <class 'str'> and type of ('Rajkumar',) is printed as <class 'tuple'> .

Characteristics of a Tuple in Python

Python tuple is indexed , ordered and immutable(unchangeable) collection of items .It also allows duplicate values .

Python tuple is indexed | How to access elements of tuple in Python ?

We can access elements from a tuple using its index . So first we need to know about how indexing works in Python tuple . For this reason we need to see the below image –

From the above image we can see that in Python index starts from 0 . So , index of "Apple" is 0 , index of True is 1 and so on . We can also see that length of the given tuple is 5 but the last index number is 4 .

There is also one concept in Python that is negative indexing . Negative indexing in Python starts from -1 which points to the last element . We can see from the above image that -1 index points to the last element "Banana" , -2 index points to the 2nd last character "Mango" .

Example 1:

mytuple = ("Apple",True,100,"Mango","Banana")

# Accessing first element
print("mytuple[0] =",mytuple[0])

# Accessing second element
print("mytuple[1] =",mytuple[1])

# Accessing last element
print("mytuple[len(mytuple)-1] =",mytuple[len(mytuple)-1])
mytuple[0] = Apple
mytuple[1] = True
mytuple[len(mytuple)-1] = Banana
  • In the above code first we have declared a tuple mytuple as ("Apple",True,100,"Mango","Banana")
  • Then we have printed first element of the tuple by mytuple[0] that is "Apple"
  • After that we have printed second element of the tuple by mytuple[1] that is True
  • Then we have printed last element of the tuple by mytuple[len(mytuple)-1] that is "Banana" . As length of the tuple is 5 so mytuple[len(mytuple)-1] treated as mytuple[4] .

To learn about len() function click here

Example 2:

mytuple = ("Apple",True,100,"Mango","Banana")

# Accessing last element
print("mytuple[-1] =",mytuple[-1])

# Accessing second last element
print("mytuple[-2] =",mytuple[-2])

# Accessing first element
print("mytuple[-len(mytuple)] =",mytuple[-len(mytuple)])
mytuple[-1] = Banana
mytuple[-2] = Mango
mytuple[-len(mytuple)] = Apple
  • In the above code first we have declared a tuple mytuple as ("Apple",True,100,"Mango","Banana")
  • Then we have printed last element of the tuple by mytuple[-1] that is "Banana"
  • After that we have printed second last element of the tuple by mytuple[-2] that is "Mango"
  • Then we have printed first element of the tuple by mytuple[-len(mytuple)] that is "Apple" . As length of the tuple is 5 so mytuple[-len(mytuple)] treated as mytuple[-5] .

Note :

If we give index outside the range then it will give IndexError .

mytuple = ("Apple",True,100,"Mango","Banana")
print(mytuple[5])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_2668/921415738.py in <module>
      1 mytuple = ("Apple",True,100,"Mango","Banana")
----> 2 print(mytuple[5])

IndexError: tuple index out of range

In the above code as the length of the tuple is 5 so index of last character will be (5-1)=4 . For this reason when we have given index as 5 Python has raised an IndexError .

Python tuple is ordered

Tuple items are ordered it means that it maintains a defined order and we can not change it .

Python tuple is immutable | How to update a tuple in Python ?

Python tuple is immutable it means we can not change , delete or add items in the tuple . If we try to do any modification in a tuple it will raise TypeError .

Example 1:

mytuple = ("Apple",True,100,"Mango","Banana")

# Accessing third element before changing
print("Before changing =",mytuple[2])

# changing the element
mytuple[2]=None
Before changing = 100
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_2668/2350219220.py in <module>
      5 
      6 # changing the element
----> 7 mytuple[2]=None

TypeError: 'tuple' object does not support item assignment
  • In the above code first we have printed the third element of the tuple which printed 100
  • Then when we have tried to change the third element it has raised an TypeError .

Example 2:

However we can always change the tuple by redeclaring the same variable with another value

mytuple = ("Apple",True,100,"Mango","Banana")

# printing the old tuple
print(mytuple)

# redeclaring mytuple another tuple
mytuple = ("Apple",True,None,"Mango","Banana")

# printing the new tuple
print(mytuple)
('Apple', True, 100, 'Mango', 'Banana')
('Apple', True, None, 'Mango', 'Banana')

In the above code we have simply changed the tuple just by redeclaring the same variable with another value .

Python tuple allows duplicate values

Python tuple allows duplicate values it means more than one element in the tuple can have same value

Example :

mytuple = ("Apple",True,100,"Apple","Banana")
print(mytuple)
('Apple', True, 100, 'Apple', 'Banana')

In the above code we can see that Python tuple has accepted duplicate values .

Slicing in Python Tuple

We can slice one or more element from a tuple using its index .

Syntax of Slicing

object[start : stop : step]

Parameters of Slicing

  • start = Optional , start specifies index number from where slicing will start . Default value is 0 .
  • Stop = Optional , stop specifies index number at where slicing will end but this number is excluded . Default value is (length of the object) .
  • step = Optional , An integer number which specifies the incrementation . Default is 1

Return type of Slicing

It returns a copy of the given datatype .

Example 1:

mytuple = ("Apple",True,100,"Mango","Banana")

# if nothing is given 
# it will print the full tuple
print("mytuple[::] =",mytuple[::])

# slicing 2nd element to 3rd element
print("mytuple[1:3] =",mytuple[1:3])
# as index of 3rd element is 2 and stop 
# parameter is excluded so we need to give 
# stop parameter as 2+1=3

# if start parameter is not given
# then python will take it as 0
print("mytuple[:3] =",mytuple[:3])

# if stop parameter is not given
# then python will take it as len(mytuple)-1
print("mytuple[2:] =",mytuple[2:])

# if we want to print 1st ,3rd and 5th character
# then we need to give step parameter as 2
print("mytuple[0:5:2] =",mytuple[0:5:2])

# by default python takes step parameter as 1
mytuple[::] = ('Apple', True, 100, 'Mango', 'Banana')
mytuple[1:3] = (True, 100)
mytuple[:3] = ('Apple', True, 100)
mytuple[2:] = (100, 'Mango', 'Banana')
mytuple[0:5:2] = ('Apple', 100, 'Banana')

In the above code we have seen various examples about slicing of tuple in Python .

Example 2:

mytuple = ("Apple",True,100,"Mango","Banana")

# slicing using negative indexing
# slicing 2nd last character to 3rd last character
print("mytuple[-2:-4:-1] =",mytuple[-2:-4:-1])
# as index of 3rd last character is -3 and stop 
# parameter is excluded so we need to give 
# stop parameter as -(3+1)=-4
# but to go -2 to -4 we need to give step as -1

# if we want to print last ,3rd last and 5th last character
# then we need to give step parameter as 2
print("mytuple[-1:-6:-2] =",mytuple[-1:-6:-2])
mytuple[-2:-4:-1] = ('Mango', 100)
mytuple[-1:-6:-2] = ('Banana', 100, 'Apple')

Note :

When we use negative step parameter then default value of start and stop parameter becomes -1 and -(length of the object) .

Example :
mytuple = ("Apple",True,100,"Mango","Banana")

# when start and stop parameter both is not given
# python takes start and stop as -1 and -5
print("mytuple[::-1] =",mytuple[::-1])
# in this example we just reverse the tuple

# when stop parameter is not given python takes stop as -5
print("mytuple[2::-1] =",mytuple[2::-1])

# when start parameter is not given python takes start as -1
print("mytuple[:3:-1] =",mytuple[:3:-1])
mytuple[::-1] = ('Banana', 'Mango', 100, True, 'Apple')
mytuple[2::-1] = (100, True, 'Apple')
mytuple[:3:-1] = ('Banana',)

How to delete a tuple in Python ?

We can delete a tuple in Python using del keyword . But if we want to access the tuple after deleting it using del keyword it will raise a NameError .

Example :

mytuple = ("Apple",True,100,"Mango","Banana")

# printing the tuple before deleting
print(mytuple)

# delete the tuple
del mytuple

# printing the tuple after deleting
print(mytuple)
('Apple', True, 100, 'Mango', 'Banana')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_2668/2324090064.py in <module>
      8 
      9 # printing the tuple after deleting
---> 10 print(mytuple)

NameError: name 'mytuple' is not defined

Iterating a tuple in Python

We can iterate a tuple in Python using for-loop and while-loop .

Example 1:

# for loop with tuple as iterator
mytuple = ('Apple', True, 100, 'Mango', 'Banana')
for element in mytuple:
    print(element)
Apple
True
100
Mango
Banana

In the above code we have iterated all element from mytuple using for-loop .

Example 2:

# python while loop with tuple datatype
mytuple = ('Apple', True, 100, 'Mango', 'Banana')
number=0
while number < len(mytuple):
    print(mytuple[number])
    number+=1
Apple
True
100
Mango
Banana

In the above code we have iterated all character from mytuple using while-loop

Nested Tuple in Python

When we use tuple inside a tuple then it is called Nested tuple . Earlier we have seen that tuple items can be of any datatype . So tuple item can be a tuple .

Example :

# nested tuple in python
mytuple = ('Apple', True, 100, 'Mango', 'Banana',("Rajkumar","sourav"))
print(mytuple)
('Apple', True, 100, 'Mango', 'Banana', ('Rajkumar', 'sourav'))

In the above code we have seen that Python accepts a tuple as tuple item .

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply