Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable.
Python
# Note : In case of list, we use square
# brackets []. Here we use round brackets ()
t = (10, 20, 30)
print(t)
print(type(t))
Output(10, 20, 30)
<class 'tuple'>
What is Immutable in Tuples?
Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in Python.
- Like Lists, tuples are ordered and we can access their elements using their index values
- We cannot update items to a tuple once it is created.
- Tuples cannot be appended or extended.
- We cannot remove items from a tuple once it is created.
Let us see this with an example.
Python
t = (1, 2, 3, 4, 5)
# tuples are indexed
print(t[1])
print(t[4])
# tuples contain duplicate elements
t = (1, 2, 3, 4, 2, 3)
print(t)
# updating an element
t[1] = 100
print(t)
Output:
2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "Solution.py", line 12, in <module>
t[1] = 100
TypeError: 'tuple' object does not support item assignment
Accessing Values in Python Tuples
Tuples in Python provide two ways by which we can access the elements of a tuple.
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.
Python
t = (10, 5, 20)
print("Value in t[0] = ", t[0])
print("Value in t[1] = ", t[1])
print("Value in t[2] = ", t[2])
OutputValue in t[0] = 10
Value in t[1] = 5
Value in t[2] = 20
Access Tuple using Negative Index
In the above methods, we use the positive index to access the value in Python, and here we will use the negative index within [].
Python
t = (10, 5, 20)
print("Value in t[-1] = ", t[-1])
print("Value in t[-2] = ", t[-2])
print("Value in t[-3] = ", t[-3])
OutputValue in t[-1] = 20
Value in t[-2] = 5
Value in t[-3] = 10
Below are the different operations related to tuples in Python:
Traversing Items of Python Tuples
Like List Traversal, we can traverse through a tuple using for loop.
Python
# Define a tuple
t = (1, 2, 3, 4, 5)
# Traverse through each item in the tuple
for x in t:
print(x, end=" ")
Concatenation of Python Tuples
To Concatenation of Python Tuples, we will use plus operators(+).
Python
# Code for concatenating 2 tuples
t1 = (0, 1, 2, 3)
t2 = ('python', 'geek')
# Concatenating above two
print(t1 + t2)
Output(0, 1, 2, 3, 'python', 'geek')
Nesting of Python Tuples
A nested tuple in Python means a tuple inside another tuple.
Python
# Code for creating nested tuples
t1 = (0, 1, 2, 3)
t2 = ('python', 'geek')
t3 = (t1, t2)
print(t3)
Output((0, 1, 2, 3), ('python', 'geek'))
Repetition Python Tuples
We can create a tuple of multiple same elements from a single element in that tuple.
Python
# Code to create a tuple with repetition
t = ('python',)*3
print(t)
Output('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’.
Slicing Tuples in Python
Slicing a Python tuple means dividing a tuple into small tuples using the indexing method. In this example, we slice the tuple from index 1 to the last element. In the second print statement, we printed the tuple using reverse indexing. And in the third print statement, we printed the elements from index 2 to 4.
Python
# code to test slicing
t = (0 ,1, 2, 3)
print(t[1:])
print(t[::-1])
print(t[2:4])
Output(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
Note: In Python slicing, the end index provided is not included.
Deleting a Tuple in Python
In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of error because after deleting the tuple, it will give a NameError.
Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del keyword.
Python
# Code for deleting a tuple
t = ( 0, 1)
del t
print(t)
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
print(t)
NameError: name 't' is not defined
Finding the Length of a Python Tuple
To find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.
Python
# Code for printing the length of a tuple
t = ('python', 'geek')
print(len(t))
Multiple Data Types With Tuple
Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple datatypes.
Python
# tuple with different datatypes
t = ("immutable", True, 23)
print(t)
Output('immutable', True, 23)
Converting a List to a Tuple
We can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its parameters.
Python
# Code for converting a list and a string into a tuple
a = [0, 1, 2]
t = tuple(a)
print(t)
Output:
Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are taken as elements), and converts them to a tuple.
Tuples in a Loop
We can also create a tuple with a single element in it using loops.
Python
# python code for creating tuples in a loop
t = ('gfg',)
# Number of time loop runs
n = 5
for i in range(int(n)):
t = (t,)
print(t)
Output(('gfg',),)
((('gfg',),),)
(((('gfg',),),),)
((((('gfg',),),),),)
(((((('gfg',),),),),),)
Different Ways of Creating a Tuple
- Using round brackets
- Without Brackets
- Tuple Constructor
- Empty Tuple
- Single Element Tuple
- Using Tuple Packing
Using Round Brackets
Python
t = ("gfg", "Python")
print(t)
Using Comma Separated
Python
# Creating a tuple without brackets
t = 4, 5, 6
print(t) # Output: (4, 5, 6)
Using Tuple Constructor
Python
# Creating a tuple using the tuple() constructor
t = tuple([7, 8, 9])
print(t) # Output: (7, 8, 9)
Creating an Empty Tuple
Python
# Creating an empty tuple
t = ()
print(t) # Output: ()
Single Element Tuple
Python
# Creating a single-element tuple
t = (10, ) # Comma is important here
print(t) # Output: (10,)
print(type(t))
# What if we do not use comma
t = (10) # This an integer (not a tuple)
print(t)
print(type(t))
Output(10,)
<class 'tuple'>
10
<class 'int'>
Tuple Packing
Python
# Tuple packing
a, b, c = 11, 12, 13
t = (a, b, c)
print(t) # Output: (11, 12, 13)
Similar Reads
Python Tuples
A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
7 min read
Tuples in Python
Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable. [GFGTABS] Python # Note : In case of list,
6 min read
Create a List of Tuples in Python
List of tuple is used to store multiple tuples together into List. We can create a list that contains tuples as elements. This practice is useful for memory efficiency and data security as tuples are immutable. The simplest way to create a list of tuples is to define it manually by specifying the va
4 min read
Create a tuple from string and list - Python
Sometimes, we can have a problem in which we need to construct a new container with elements from different containers. This kind of problem can occur in domains in which we use different types of data. Let's discuss ways to convert string and list data to tuple. Create a tuple from string and list
5 min read
Access front and rear element of Python tuple
Sometimes, while working with records, we can have a problem in which we need to access the initial and last data of a particular record. This kind of problem can have application in many domains. Let's discuss some ways in which this problem can be solved. Method #1: Using Access Brackets We can pe
6 min read
Python - Element Index in Range Tuples
Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let's discuss certain ways in which this t
6 min read
Unpacking a Tuple in Python
Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment
3 min read
Python | Unpacking nested tuples
Sometimes, while working with Python list of tuples, we can have a problem in which we require to unpack the packed tuples. This can have a possible application in web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension This task can be p
6 min read
Python | Slice String from Tuple ranges
Sometimes, while working with data, we can have a problem in which we need to perform the removal from strings depending on specified substring ranges. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + list slicing: This is the brute force task to perform this t
3 min read
Python - Clearing a tuple
Sometimes, while working with Records data, we can have a problem in which we may require to perform clearing of data records. Tuples, being immutable cannot be modified and hence makes this job tough. Let's discuss certain ways in which this task can be performed. Method #1 : Using list() + clear()
4 min read
Python program to remove last element from Tuple
Given a tuple, the task is to write a Python program to delete the last element in the tuple in Python. Example: Input: ("geeks", "for", "geeks") Output:("geeks", "for") Explanation: Here we are deleting the last element of the tuple and finally modifying the original one. Note: Tuples are immutable
3 min read
Python | Removing duplicates from tuple
Many times, while working with Python tuples, we can have a problem removing duplicates. This is a very common problem and can occur in any form of programming setup, be it regular programming or web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using set()
4 min read
Python - AND operation between Tuples
Sometimes, while working with records, we might have a common problem of performing AND operation contents of one tuple with corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records especially Data Science. Let’s discuss certain ways in w
4 min read
Python - Sum of tuple elements
Sometimes, while programming, we have a problem in which we might need to perform summation among tuple elements. This is an essential utility as we come across summation operations many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task
6 min read
Python | Ways to concatenate tuples
Many times, while working with records, we can have a problem in which we need to add two records and store them together. This requires concatenation. As tuples are immutable, this task becomes little complex. Let's discuss certain ways in which this task can be performed. Method #1 : Using + opera
6 min read
Python | Repeating tuples N times
Sometimes, while working with data, we might have a problem in which we need to replicate, i.e construct duplicates of tuples. This is an important application in many domains of computer programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using * operator The mu
5 min read
Python Membership and Identity Operators
There is a large set of Python operators that can be used on different datatypes. Sometimes we need to know if a value belongs to a particular set. This can be done by using the Membership and Identity Operators. In this article, we will learn about Python Membership and Identity Operators. Table of
5 min read
Python | Compare tuples
Sometimes, while working with records, we can have a problem in which we need to check if each element of one tuple is greater/smaller than it's corresponding index in other tuple. This can have many possible applications. Let's discuss certain ways in which this task can be performed. Method #1 : U
4 min read
How to Join a list of tuples into one list?
In Python, we may sometime need to convert a list of tuples into a single list containing all elements. Which can be done by several methods. The simplest way to join a list of tuples into one list is by using nested for loop to iterate over each tuple and then each element within that tuple. Let's
2 min read
Python - Join Tuples if similar initial element
Sometimes, while working with Python tuples, we can have a problem in which we need to perform concatenation of records from the similarity of initial element. This problem can have applications in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Inp
8 min read
Python - Create list of tuples using for loop
In this article, we will discuss how to create a List of Tuples using for loop in Python. Let's suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index. Method 1: Using For loop with append
2 min read
How to iterate through list of tuples in Python
In Python, a list of tuples is a common data structure used to store paired or grouped data. Iterating through this type of list involves accessing each tuple one by one and sometimes the elements within the tuple. Python provides several efficient and versatile ways to do this. Let’s explore these
2 min read
Python Tuple Methods
Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples. Count() MethodThe count() method of Tuple returns the number of times the given
3 min read
Python Tuple Exercise
Basic Tuple ProgramsPython program to Find the size of a TuplePython – Maximum and Minimum K elements in TupleCreate a list of tuples from given list having number and its cube in each tuplePython – Adding Tuple to List and vice – versaPython – Sum of tuple elementsPython – Modulo of tuple elementsP
3 min read