The Wayback Machine - https://web.archive.org/web/20241009091023/https://www.geeksforgeeks.org/tuples-in-python/
Open In App

Tuples in Python

Last Updated : 06 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python Tuple is a collection of objects separated by commas. In some ways, 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.

Creating Python Tuples

There are various ways by which you can create a tuple in Python. They are as follows:

  • Using round brackets
  • With one item
  • Tuple Constructor

Create Tuples using Round Brackets ()

To create a tuple we will use () operators.

Python3




var = ("Geeks", "for", "Geeks")
print(var)


Output:

('Geeks', 'for', 'Geeks')

Create a Tuple With One Item

Python 3.11 provides us with another way to create a Tuple.

Python3




values : tuple[int | str, ...] = (1,2,4,"Geek")
print(values)


Output:

Here, in the above snippet we are considering a variable called values which holds a tuple that consists of either int or str, the ‘…’ means that the tuple will hold more than one int or str.

(1, 2, 4, 'Geek')

Note: In case your generating a tuple with a single element, make sure to add a comma after the element. Let us see an example of the same.

Python3




mytuple = ("Geeks",)
print(type(mytuple))
 
#NOT a tuple
mytuple = ("Geeks")
print(type(mytuple))


Output:

<class 'tuple'>
<class 'str'>

Tuple Constructor in Python

To create a tuple with a Tuple constructor, we will pass the elements as its parameters.

Python3




tuple_constructor = tuple(("dsa", "developement", "deep learning"))
print(tuple_constructor)


Output :

('dsa', 'developement', 'deep learning')

What is Immutable in Tuples?

Tuples in Python are similar to Python lists but not entirely. Tuples are immutable and ordered and allow duplicate values. Some Characteristics of Tuples in Python.

  • We can find items in a tuple since finding any item does not make changes in the tuple.
  • One cannot add 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.

Python3




mytuple = (1, 2, 3, 4, 5)
 
# tuples are indexed
print(mytuple[1])
print(mytuple[4])
 
# tuples contain duplicate elements
mytuple = (1, 2, 3, 4, 2, 3)
print(mytuple)
 
# adding an element
mytuple[1] = 100
print(mytuple)


Output:

Python tuples are ordered and we can access their elements using their index values. They are also immutable, i.e., we cannot add, remove and change the elements once declared in the tuple, so when we tried to add an element at index 1, it generated the error.

2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
  File "e0eaddff843a8695575daec34506f126.py", line 11, in
    tuple1[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.

  • Using a positive index
  • Using a negative index

Python Access Tuple using a Positive Index

Using square brackets we can get the values from tuples in Python.

Python3




var = ("Geeks", "for", "Geeks")
 
print("Value in Var[0] = ", var[0])
print("Value in Var[1] = ", var[1])
print("Value in Var[2] = ", var[2])


Output:

Value in Var[0] =  Geeks
Value in Var[1] =  for
Value in Var[2] =  Geeks

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 [].

Python3




var = (1, 2, 3)
 
print("Value in Var[-1] = ", var[-1])
print("Value in Var[-2] = ", var[-2])
print("Value in Var[-3] = ", var[-3])


Output:

Value in Var[-1] =  3
Value in Var[-2] =  2
Value in Var[-3] =  1

Different Operations Related to Tuples

Below are the different operations related to tuples in Python:

  • Concatenation
  • Nesting
  • Repetition
  • Slicing
  • Deleting
  • Finding the length
  • Multiple Data Types with tuples
  • Conversion of lists to tuples
  • Tuples in a Loop

Concatenation of Python Tuples

To Concatenation of Python Tuples, we will use plus operators(+).

Python3




# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
 
# Concatenating above two
print(tuple1 + tuple2)


Output:

(0, 1, 2, 3, 'python', 'geek')

Nesting of Python Tuples

A nested tuple in Python means a tuple inside another tuple.

Python3




# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
 
tuple3 = (tuple1, tuple2)
print(tuple3)


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.

Python3




# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)


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.

Python3




# code to test slicing
tuple1 = (0 ,1, 2, 3)
 
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])


Output:

In this example, we sliced 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.

(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.

Python3




# Code for deleting a tuple
tuple3 = ( 0, 1)
 
del tuple3
print(tuple3)


Output:

Traceback (most recent call last):
  File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
    print(tuple3)
NameError: name 'tuple3' 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.

Python3




# Code for printing the length of a tuple
tuple2 = ('python', 'geek')
print(len(tuple2))


Output:

 2

Multiple Data Types With Tuple

Tuples in Python are heterogeneous in nature. This means tuples support elements with multiple datatypes.

Python3




# tuple with different datatypes
tuple_obj = ("immutable",True,23)
print(tuple_obj)


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.

Python3




# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
 
print(tuple(list1))
 
# string 'python'
print(tuple('python'))


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.

(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')

Tuples in a Loop

We can also create a tuple with a single element in it using loops.

Python3




# python code for creating tuples in a loop
tup = ('geek',)
 
# Number of time loop runs
n = 5
for i in range(int(n)):
    tup = (tup,)
    print(tup)


Output:

(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),)


Previous Article
Next Article

Similar Reads

Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a
3 min read
Python | Sort Tuples in Increasing Order by any key
Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] E
3 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Python | Remove empty tuples from a list
In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples: Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]Output : [('ram', '15',
8 min read
Python | Filter dictionary of tuples by condition
Sometimes, we can have a very specific problem in which we are given a tuple pair as values in dictionary and we need to filter dictionary items according to those pairs. This particular problem as use case in Many geometry algorithms in competitive programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using items
3 min read
Python | Unzip a list of tuples
The zipping technique, that is assigning a key value or pairing from two different lists has been covered in many articles before, sometimes we have a specific utility to perform the reverse task. This task can be achieved by various methods. Let's discuss some of the methods to unzip a list of tuples. Method #1: Using List comprehension Using list
5 min read
Python | Accessing nth element from tuples in list
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem. Method #1 : Using list comprehe
8 min read
Python | Linear search on list or tuples
Let us see a basic linear search operation on Python lists and tuples. A simple approach is to do a linear search, that is Start from the leftmost element of the list and one by one compare x with each element of the list.If x matches with an element, return True.If x doesn’t match with any of the elements, return False. Example #1: Linear Search o
2 min read
Python | Position Summation in List of Tuples
Sometimes the data that we receive is in the form of tuples having data from various sources and we can usually have a use case in which we require to process the sum of each index of tuple for cumulation. Let's discuss certain ways in which this can be performed. Method #1: Using list comprehension This is the most naive method to perform this par
7 min read
Python | Get sum of tuples having same first value
Given a list of tuples, the task is to sum the tuples having the same first value. Examples: Input: [(1, 13), (2, 190), (3, 82), (1, 12)] Output: [(1, 25), (2, 190), (3, 82)]Input: [(1, 13), (1, 190), (3, 25), (1, 12)] Output: [(1, 215), (3, 25)] Let us discuss the different ways we can do this task. Method #1: Using map() C/C++ Code # Python code
6 min read
Python | Preceding element tuples in list
Sometimes, while working with Python list, we can have a problem in which we need to construct tuples, with the preceding element, whenever that element matches a particular condition. This can have potential application in day-day programming. Let's discuss a way in which this task can be performed. Method #1: Using for loop C/C++ Code # Python3 c
5 min read
Python | Convert Numpy Arrays to Tuples
Given a numpy array, write a program to convert numpy array into tuples. Examples - Input: ([[1, 0, 0, 1, 0], [1, 2, 0, 0, 1]]) Output: ((1, 0, 0, 1, 0), (1, 2, 0, 0, 1)) Input: ([['manjeet', 'akshat'], ['nikhil', 'akash']]) Output: (('manjeet', 'akshat'), ('nikhil', 'akash')) Method #1: Using tuple and map Step-by-step approach : Import the NumPy
2 min read
How we can iterate through list of tuples in Python
In this article, we will discuss different ways to iterate the list of tuples in Python. It can be done in these ways: Using Loop.Using enumerate().Method 1: Using Loop Here we are going to form a list of tuples using for loop. C/C++ Code # create a list of tuples with student # details name = [('sravan',7058,98.45), ('ojaswi',7059,90.67), ('bobby'
2 min read
Python Memory Consumption: Dictionary VS List of Tuples
In this article, we are going to see memory consumption in dictionaries and a list of tuples. Memory Consumption by dict vs list of tuples Dictionary occupies much more space than a list of tuples. Even an empty dict occupies much space as compared to a list of tuples. Example 1: As we can clearly see that there is a huge difference between memory
4 min read
Python - Dict of tuples to JSON
In this article, we will discuss how to convert a dictionary of tuples to JSON. Method 1: Using json.dumps() This will convert dictionary of tuples to json Syntax: json.dumps(dictionary, indent) Parameters: dictionary is the input dictionary.indent specify the number of units of indentation Example: Python dict of tuples to json conversion C/C++ Co
2 min read
Make Scatter Plot From Set of Points in Python Tuples
Now we'll look at an example that shows how to use scatter and how scatter values can be passed to a function as a tuple argument. Assume your function takes four and five arguments each argument will be passed as a separate single data point or value to plot the scatter chart. Let's see the implementation of it in Python. What is Scatter in Python
3 min read
Python - Create a List of Tuples
List and tuples both are data structures in Python, with some differences. Lists are mutable data structures whereas tuples are immutable (can not be changed after creating it). We can make a list that contains tuples as elements. This practice is useful for data structuring, memory efficiency, and data security as tuples are immutable. In this art
4 min read
Output of python program | Set 12(Lists and Tuples)
Prerequisite: List and Tuples Note: Output of all these programs is tested on Python3 1) What is the output of the following program? C/C++ Code L1 = [] L1.append([1, [2, 3], 4]) L1.extend([7, 8, 9]) print(L1[0][1][1] + L1[2]) a) Type Error: can only concatenate list (not "int") to list b) 12 c) 11 d) 38 Ans: (c) Explanation: In the print(), indexi
3 min read
Convert List Of Tuples To Json Python
Working with data often involves converting between different formats, and JSON is a popular choice for data interchange due to its simplicity and readability. In Python, converting a list of tuples to JSON can be achieved through various approaches. In this article, we'll explore four different methods, each offering its own advantages in differen
3 min read
Output of Python Programs | Set 20 (Tuples)
Prerequisite: Tuples Note: The output of all these programs is tested on Python3 1. What will be the output of the following program? [GFGTABS] Python3 tuple = (1, 2, 3, 4) tuple.append( (5, 6, 7) ) print(len(tuple)) [/GFGTABS]Options: 125Error Output: 4. ErrorExplanation: In this case an exception will be thrown as tuples are immutable and don’t h
2 min read
Python Tuples
Python Tuple is a collection of Python Programming objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers.  Values of a tuple are syntactically separated by 'commas'. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses. Th
9 min read
Creating a Pandas DataFrame using Dict of Tuples in Python
Working with Python dictionaries containing tuples is a common scenario, especially when dealing with heterogeneous data. Transforming this data into a Pandas DataFrame allows for efficient manipulation and analysis. In this article, we will see how we can convert a dictionary with a tuple into a DataFrame in Python. Convert Dictionary with Tuple i
2 min read
Create PySpark DataFrame from list of tuples
In this article, we are going to discuss the creation of a Pyspark dataframe from a list of tuples. To do this, we will use the createDataFrame() method from pyspark. This method creates a dataframe from RDD, list or Pandas Dataframe. Here data will be the list of tuples and columns will be a list of column names. Syntax: dataframe = spark.createDa
2 min read
Convert PySpark dataframe to list of tuples
In this article, we are going to convert the Pyspark dataframe into a list of tuples. The rows in the dataframe are stored in the list separated by a comma operator. So we are going to create a dataframe by using a nested list Creating Dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sq
2 min read
How to convert 1D array of tuples to 2D Numpy array?
In this article, we will discuss how to convert a 1D array of tuples into a numpy array. Example: Input: [(1,2,3),('Hi','Hello','Hey')] Output: [['1' '2' '3'] ['Hi' 'Hello' 'Hey']] #NDArray Method 1: Using Map The map is a function used to execute a function for each item in an Iterable i.e array. Example: Here, we first are importing Numpy and def
2 min read
How to extract a particular column from 1D array of tuples?
In this article, we will cover how to extract a particular column from a 1-D array of tuples in python. Example Input: [(18.18,2.27,3.23),(36.43,34.24,6.6),(5.25,6.16,7.7),(7.37,28.8,8.9)] Output: [3.23, 6.6 , 7.7 , 8.9 ] Explanation: Extracting the 3rd column from 1D array of tuples. Method 1: Using Slice As a first step let us first define a 1D a
2 min read
Creating a Pandas dataframe using list of tuples
Pandas is famous for data manipulation in Python. We can create a DataFrame from a list of simple tuples, and can even choose the specific elements of the tuples we want to use. Using pd.DataFrame() functionHere we will create a Pandas Dataframe using a list of tuples with the pd.DataFrame() function. Example 1: In this example, we will simply pass
2 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Practice Tags :