Open In App

Python Tuples

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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. This helps in understanding the Python tuples more easily.

Creating a Tuple

In Python Programming, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping the data sequence.

Note: Creation of Python tuple without the use of parentheses is known as Tuple Packing.  

Python Program to Demonstrate the Addition of Elements in a Tuple.

Python3
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

# Creating a Tuple
# with the use of string
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

Output: 

Initial empty Tuple: 
()

Tuple with the use of String:
('Geeks', 'For')

Tuple using List:
(1, 2, 4, 5, 6)

Tuple with the use of function:
('G', 'e', 'e', 'k', 's')

Creating a Tuple with Mixed Datatypes.

Python Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple. 

Python3
# Creating a Tuple
# with Mixed Datatype
Tuple1 = (5, 'Welcome', 7, 'Geeks')
print("\nTuple with Mixed Datatypes: ")
print(Tuple1)

# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

# Creating a Tuple
# with repetition
Tuple1 = ('Geeks',) * 3
print("\nTuple with repetition: ")
print(Tuple1)

# Creating a Tuple
# with the use of loop
Tuple1 = ('Geeks')
n = 5
print("\nTuple with a loop")
for i in range(int(n)):
    Tuple1 = (Tuple1,)
    print(Tuple1)

Output: 

Tuple with Mixed Datatypes: 
(5, 'Welcome', 7, 'Geeks')

Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))

Tuple with repetition:
('Geeks', 'Geeks', 'Geeks')

Tuple with a loop
('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
((((('Geeks',),),),),)

Time complexity: O(1)
Auxiliary Space : O(n)

Python Tuple Operations

Here, below are the Python tuple operations.

  • Accessing of Python Tuples
  • Concatenation of Tuples
  • Slicing of Tuple
  • Deleting a Tuple

Accessing of Tuples

In Python Programming, Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that are accessed via unpacking or indexing (or even by attribute in the case of named tuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

Note: In unpacking of tuple number of variables on the left-hand side should be equal to a number of values in given tuple a. 

Python3
# Accessing Tuple
# with Indexing
Tuple1 = tuple("Geeks")
print("\nFirst element of Tuple: ")
print(Tuple1[0])


# Tuple unpacking
Tuple1 = ("Geeks", "For", "Geeks")

# This line unpack
# values of Tuple1
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)

Output: 

First element of Tuple: 
G

Values after unpacking:
Geeks
For
Geeks

Time complexity: O(1)
Space complexity: O(1)

Concatenation of Tuples

Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done by the use of ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple. Other arithmetic operations do not apply on Tuples. 

Note- Only the same datatypes can be combined with concatenation, an error arises if a list and a tuple are combined. 

Python3
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'For', 'Geeks')

Tuple3 = Tuple1 + Tuple2

# Printing first Tuple
print("Tuple 1: ")
print(Tuple1)

# Printing Second Tuple
print("\nTuple2: ")
print(Tuple2)

# Printing Final Tuple
print("\nTuples after Concatenation: ")
print(Tuple3)

Output: 

Tuple 1: 
(0, 1, 2, 3)

Tuple2:
('Geeks', 'For', 'Geeks')

Tuples after Concatenation:
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')

Time Complexity: O(1)
Auxiliary Space: O(1)

Slicing of Tuple

Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing can also be done to lists and arrays. Indexing in a list results to fetching a single element whereas Slicing allows to fetch a set of elements. 

Note- Negative Increment values can also be used to reverse the sequence of Tuples. 

Python3
# Slicing of a Tuple

# Slicing of a Tuple
# with Numbers
Tuple1 = tuple('GEEKSFORGEEKS')

# Removing First element
print("Removal of First Element: ")
print(Tuple1[1:])

# Reversing the Tuple
print("\nTuple after sequence of Element is reversed: ")
print(Tuple1[::-1])

# Printing elements of a Range
print("\nPrinting elements between Range 4-9: ")
print(Tuple1[4:9])

Output: 

Removal of First Element: 
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')

Tuple after sequence of Element is reversed:
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')

Printing elements between Range 4-9:
('S', 'F', 'O', 'R', 'G')

Time complexity: O(1)
Space complexity: O(1)

Deleting a Tuple

Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple gets deleted by the use of del() method. 

Note- Printing of Tuple after deletion results in an Error. 

Python
# Deleting a Tuple

Tuple1 = (0, 1, 2, 3, 4)
del Tuple1

print(Tuple1)

Output

Traceback (most recent call last): 
File "/home/efa50fd0709dec08434191f32275928a.py", line 7, in 
print(Tuple1) 
NameError: name 'Tuple1' is not defined

Built-In Methods

Built-in-MethodDescription
index( )Find in the tuple and returns the index of the given value where it’s available
count( )Returns the frequency of occurrence of a specified value

Built-In Functions

Built-in FunctionDescription
all()Returns true if all element are true or if tuple is empty
any()return true if any element of the tuple is true. if tuple is empty, return false
len()Returns length of the tuple or size of the tuple
enumerate()Returns enumerate object of tuple
max()return maximum element of given tuple
min()return minimum element of given tuple
sum()Sums up the numbers in the tuple
sorted()input elements in the tuple and return a new sorted list
tuple()Convert an iterable to a tuple.

Tuples VS Lists:

SimilaritiesDifferences

Functions that can be used for both lists and tuples:

len(), max(), min(), sum(), any(), all(), sorted()

Methods that cannot be used for tuples:

append(), insert(), remove(), pop(), clear(), sort(), reverse()

Methods that can be used for both lists and tuples:

count(), Index()

we generally use ‘tuples’ for heterogeneous (different) data types and ‘lists’ for homogeneous (similar) data types.
Tuples can be stored in lists.Iterating through a ‘tuple’ is faster than in a ‘list’.
Lists can be stored in tuples.‘Lists’ are mutable whereas ‘tuples’ are immutable.
Both ‘tuples’ and ‘lists’ can be nested.Tuples that contain immutable elements can be used as a key for a dictionary.

Recent Articles on Tuple

Tuples Programs

Useful Links:



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
Tuples in Python
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 TuplesThere are various ways by which you can create a tuple i
6 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
Article Tags :
Practice Tags :
three90RightbarBannerImg