Open In App

Tuples in Python

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
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 | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python | How to Concatenate tuples to nested tuples
Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let's discuss certain ways in which this problem is solved
6 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read
Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements. Examples: Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements. Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple wit
10 min read
Practice Tags :