×

Tuples in Python

A tuple is an immutable sequence of Python objects. Similar to lists, tuples are sequential arrangements of data items. However, the elements of a tuple cannot be changed once assigned.

A tuple can hold any number of items and they can be of different data types (int, float, string, etc.).

Table of Contents

Creating a Tuple

A tuple is created by placing all the elements separated by commas, enclosed within parentheses (). The parenthesis can be dropped but it is a good practice to use them.

There are different types of tuples in python based on the values of the data items they hold.

The following code demonstrates how to create various types of tuples in python.

# Different types of tuples

# Empty tuple
temp_tuple = ()
print(temp_tuple)

# Tuple having integers
temp_tuple = (10, 20, 30)
print(temp_tuple)

# tuple with mixed datatypes
temp_tuple = (1, "Hi", 7.9)
print(temp_tuple)

# nested tuple
temp_tuple = ("cat", [2, 4, 6], (1, 2, 3))
print(temp_tuple)

Output

()
(10, 20, 30)
(1, 'Hi', 7.9)
('cat', [2, 4, 6], (1, 2, 3))

A tuple can also be created using tuple packing, i.e., without using parenthesis.

temp_tuple = 13, 2.6, "cat"
print(temp_tuple)

# tuples can also be unpacked
x, y, z = temp_tuple

print(x)      # 13
print(y)      # 2.6
print(z)      # cat

Output

(13, 2.6, 'cat')
13
2.6
cat

Creating a tuple with one element is a bit different. Putting a single element inside parenthesis is not enough. We will need a comma at the end to indicate that it is an object of the “tuple” class.

temp_tuple = ("Hello")
print(type(temp_tuple))  # an object of the 'str' class.

# Creating a tuple having a single element
temp_tuple = ("Hello",)
print(type(temp_tuple))  # an object of the 'tuple' class.

# Enclosing within a parenthesis is optional
temp_tuple = "Hello",
print(type(temp_tuple))  # an object of the 'tuple' class.

Output

&ltclass 'str'&gt
&ltclass 'tuple'&gt
&ltclass 'tuple'&gt

Time and Space Complexity of Creating a Tuple

The time complexity of creating a tuple is O(1) because we are inserting all elements upfront. The space complexity depends on the number of elements we insert. Thus, for creating a tuple of size ‘N’, the space complexity is O(N).

Accessing a Tuple

To understand how tuples are stored in memory, we must visualize the computer memory as a grid. Like arrays and lists, the elements of tuples take up this grid in adjacent memory locations. This guarantees efficiency for locating those values.

Since the elements are stored in the memory contagiously, the process of accessing elements becomes optimized because the computer already knows where the value is located.

There are primarily three different ways that we can use to access the elements of a tuple.

Indexing

To access the elements of a tuple, we can use the method of indexing. Each data item is assigned a unique index beginning with 0. Thus, a tuple containing 7 elements will have indices from 0 to 6. If we attempt to access an index outside of this range then an IndexError will be encountered.

# Indexing to access tuple elements
temp_tuple = ('p','y','t','h','o','n')

print(temp_tuple[0])   # 'p' has the index '0' 
print(temp_tuple[5])   # 'n' has the index '5'
#Output
p
n

Likewise, nested tuples are accessed using nested indexing.

# nested tuple
nest_tuple = ("cat", [2, 4, 6], (1, 2, 3))

# nested index
print(nest_tuple[0][2])       # 't'
print(nest_tuple[1][1])       # 4
#Output
t
4

Indices can only take up integer values. If any non-integer type value is witnessed, a TypeError would be displayed.

# IndexError : displayed when index is out of range
# print(temp_tuple[6])

# Index must be an integer
# TypeError: displayed when index is not an int type
# temp_tuple[3.0]

Negative Indexing

In python, negative indexing is also allowed for sequences. Negative indices represent the elements in the opposite order.

The last element of the tuple is denoted by a negative index of ‘-1’, the second last element by ‘-2’, and so on.

# Negative indexing to access tuple elements
temp_tuple = ('p', 'y', 't', 'h', 'o', 'n')

print(temp_tuple[-1])    # 'n' has the index '-1' 

print(temp_tuple[-6])   # 'p' has the index '-6' 

Output

n
p

Slicing

In python, slicing is an operation that extracts a subset of elements from lists, tuples, etc. Tuple slicing can be performed using the ‘:’ operator to access subsets of a tuple.

Hence, if we want a range, we need the index that will slice that portion from the tuple.

# Accessing tuple elements using slicing
my_tuple = ('s','t','a','r','t','l','i','n','g')

print(my_tuple[1:4])   #the subset ('t', 'a', 'r') is displayed with indices ('1', '2', '3')

print(my_tuple[:-7])   #the subset ('s', 't') is displayed with indices ('-8', '-9')

print(my_tuple[7:])    #the subset ('n', 'g') is displayed with indices ('8', '9')

print(my_tuple[:])      #displays all elements from beginning to end

Output

('t', 'a', 'r')
('s', 't')
('n', 'g')
('s', 't', 'a', 'r', 't', 'l', 'i', 'n', 'g')

Traversing a Tuple

We can traverse or iterate over a tuple using a for loop in python. Traversing is nothing but reading elements one by one in the tuple.

# Traversing a tuple with a for loop
temp_tuple = ('a', 'b', 'c', 'd')
for i in temp_tuple:
    print(i)

#Using the range function to traverse the loop
for i in range(len(temp_tuple)):
    print(temp_tuple[i])

Output

a b c d 
a b c d

Time and Space Complexity to Traverse a Tuple

The time complexity for traversing a tuple of size ‘N’ is O(N) as we have to iterate through each of the elements. The space complexity is O(1) because for traversing tuples an additional memory is not required.

Searching an Element in a Tuple

There are two methods to search for an element in a tuple.

  • The first method is to use the “in” operator
  • The second method is to create a user defined function and iterate through the tuple, searching for the required element one by one. This method is an example of linear search.

The ‘in’ operator

Using the in-built operator ‘in’, we can simply search the item in the tuple. It returns a boolean value representing whether the data item was found or not.

#Using the 'in' opeator to search 
temp_tuple = ('w', 'x', 'y', 'z')

print('w' in temp_tuple)   #returns True as 'w' exists in the tuple

print('a' in temp_tuple)   #returns False as 'a' doesn't exist in the tuple

Output

True
False

Using a linear search function

We can create a simple linear search function to find an element in a tuple. The function will contain two parameters, one being the tuple itself and the element to be searched. Then, we’ll iterate over the tuple using a for loop and check each element.

If the required element is found, we can return its index using the in-built ‘index’ function of the ‘tuple’ class.

temp_tuple = ('w', 'x', 'y', 'z')

#Linear search function to search a tuple
def tupleSearch(rTuple, element):
       for item in rTuple:
             if item == element:
                    return rTuple.index(item)
       return 'element not found'

print(tupleSearch(temp_tuple, 'x'))    #returns '1' as the index of the element

print(tupleSearch(temp_tuple, 'a'))    #returns 'element not found' as 'a' does not exist in the tuple

Output

1
element not found

Time and Space Complexity for Linear Search in a Tuple

Let the size of the tuple be ‘N’. The time complexity for linear search will be O(N) as we have to iterate through every element while searching. The space complexity is O(1) because for linear search an additional memory is not required.

Tuple Operations and Functions

This section will discuss the various operators and in-built functions that can be performed on a tuple.

Tuple Operators

The ‘+’ operator

The ‘+’ operator is used for the concatenation of two tuples.

#Tuple concatenation
temp_tuple1 = (1,2,3,4)
temp_tuple2 = (5,6,7,8)

print(temp_tuple1 + temp_tuple2)

Output

(1, 2, 3, 4, 5, 6, 7, 8)

The ‘*’ operator

The ‘*’ operator is used between a tuple and an integer. The function of this operator is to repeat each element of the tuple as many times as the integer.

# * operator for repetition
temp_tuple = (1,2,3,4)

print(temp_tuple * 3)

Output

(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)

The ‘in’ operator

The ‘in’ operator is used to loop through all the members of a tuple and check for a given element. It returns a boolean value depending upon the search result.

# in operator for tuple
temp_tuple = (1,2,3,4)

print(4 in temp_tuple)    #returns True as 4 exists in the tuple

Output

True

Tuple Functions

The count() function

The count() function returns the number of times a certain value appears in a tuple.

temp_tuple = (1, 2, 9, 6, 9, 5, 4, 6, 6, 5)
x = temp_tuple.count(5)
print(x)

#Output
2

The index() function

The index() method returns the index of the first occurrence of the required data item. It triggers a ValueError exception when the value is not found.

temp_tuple = (2, 9, 7, 8, 7, 5, 4, 1, 8, 3)
x = temp_tuple.index(8)
print(x)

#Output
3

The len() function

The len() function returns the length/size of the given tuple.

temp_tuple = (1, 2, 3, 4, 5, 6, 7, 8)
x = len(temp_tuple)
print(x)

#Output
8

The max() function

The max() function returns the maximum arithmetic value among the data items in a tuple.

temp_tuple = (1, 2, 3, 4, 5, 6, 7, 8)
x = max(temp_tuple)
print(x)

#Output
8

The min() function

The min() function returns the maximum arithmetic value among the data items in a tuple.

temp_tuple = (1, 2, 3, 4, 5, 6, 7, 8)
x = min(temp_tuple)
print(x)

#Output
1

The tuple() function

In python, tuple() is an in-built function that is used to create a tuple.

temp_list= [ 1, 2, 3, 4 ] 
temp_tuple = tuple(temp_list)
print(temp_tuple)

#Output
(1, 2, 3, 4)

Lists vs Tuples

ListTuple
Lists are mutable.Tuples are immutable.
Lists are slower as their iterations are more time-consuming.Tuples are faster as their iterations are less time-consuming.
Operations like insertion and deletion are possible.Elements can be better accessed but there are fewer operations.
Takes up more memory.Takes up less memory.
Generally used to store elements of similar data types.Generally used to store elements of different data types.

FAQ Question in Tuples

What do you mean by a tuple in python

Tuples are used to store multiple items in a single variable. A tuple is a collection that is ordered and immutable. syntax – var = (ele1, ele2, ele3,…..)

x = (1, 2, 3, 4)

What is the use of tuple in python

Tuple assignment occurs simultaneously instead of occurring in a sequence, making it useful for swapping values.

How to create a tuple in python

Tuple can be created by enclosing values in a closed parenthesis as follows

tup = (1, 2, 3, 4)

How to access tuple in python

Tuples can be accessed by their indexes

a =(1, 2, 3, 4)

print(a)

print(a[1])

Output

(1, 2, 3, 4)
2

How to append to a tuple in python

Once a tuple is created, it is immutable. So, an element cannot be appended into a tuple.

How to check a tuple in python

type() can be used to check if a structure is a tuple.

a=(1,2,3,4)

print(type(a))

Output

<class 'tuple'>

Are tuples iterable in python

Yes, elements in a tuple are iterable.

a =(1,2,3,4)

for i in a:
    print(i)

Output

1
2
3
4

How to unpack a tuple python

Tuples can be unpacked by assigning variable names to the elements in the tuple.

fruits = ("apple", "banana", "watermelon")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)

Output

apple
banana
watermelon

What are list, tuple and dictionary in python

Lists, tuples, and dictionaries in python are data structures. List and tuples are ordered collections whereas dictionaries are an unordered collection of elements.

a = [1,2,3,4,5]
b = (1,2,3,4,5)
c = {'a':1,'b':2}

type(a)
type(b)
type(c)

Output-

<class 'list'>
<class 'tuple'>
<class 'dictionary'>

When to use tuples in python

Tuples are used in cases where a fixed and immutable list of objects are to be accessed separately.

How literals of type tuple are written in python

tuple literal is written, separated by a comma ( , ) and surrounded by parenthesis ( () ).

a = (1,2,a,3.4)

How to convert the list into a tuple in python

Typecasting to tuple from a list can be done by simply using tuple(list_name).

a =[1, 2, 3, 4]
b=tuple(a)
print(b)

Output

(1, 2, 3, 4)

What is the difference between list and tuple in python

Tuples and lists are both pairs of items, the only difference is tuples are immutable and lists are mutable.

How to add tuple to list in python

Tuples can be considered as an element when appending to a list.

a = [1, 2, 3, 4]
a.append((1, 2, 3))
print(a)

Output

[1, 2, 3, 4, (1, 2, 3)]

Can tuple be used as a dictionary key in python

Yes, tuples are hashable and can be used as dictionary keys.

coordinates = { (0,0) : 100, (1,1) : 200}
coordinates[(1,0)] = 150
coordinates[(0,1)] = 125

print(coordinates)

Output

 {(0, 0): 100, (1, 1): 200, (1, 0): 150, (0, 1): 125}

How to delete tuple in python

del() keyword can be used to delete a tuple variable.

a = [1, 2, 3, 4]
a.append((1,2,3))
del(a)
print(a)

Output

NameError: name 'a' is not defined

How to reverse a tuple in python

A tuple can be reversed by using the slice operator as follows. But it does not alter the original tuple.

tuples = ('z','a','d','f','g','e','e','k')
print(tuples[::-1])

Output

('k', 'e', 'e', 'g', 'f', 'd', 'a', 'z')

How to print a tuple in python

Tuples can be printed using print(tuple_name)

a = (1, 2, 3)
print(a)

Output

(1, 2, 3)

How to separate a tuple in python

Tuples can be separated by using a slice operator on tuple and appending the parts into a list.

tup=(7,6,8,19,2,4,13,1,10,25,11,34)
lst=[]
for i in range(0,10,3):
    lst.append((tup[i:i+3]))
print(lst)

Output

[(7, 6, 8), (19, 2, 4), (13, 1, 10), (25, 11, 34)]

How to sort tuples in python

Tuples can’t be sorted and rearranged as tuples are immutable.

How to add two tuples in python

Tuples can be concatenated by using a + operator.

print((1, 2, 3) + (4, 5, 6))

Output-

(1, 2, 3, 4, 5, 6)

How to get the first item in tuple python

The first item can be accessed by using the index as 0.

a = (1, 2, 3)
print(a[0])

Output

1

How to index tuple in python

Tuples are indexed by default from 0 to (length of tuple – 1)

How to update tuple in python

Tuples can’t be updated as they are immutable.

How to add a string to a tuple python

Elements cannot be added after creating a tuple, as tuples are immutable. But you can create a tuple with string values.

tuple1 = ("Abc", "BBC", False, 45)

How to combine tuples in python

Tuples can be concatenated by using a + operator.

print((1, 2, 3) + (4, 5, 6))

Output-

(1, 2, 3, 4, 5, 6)

How to compare tuples in python

Tuples can be compared by == operator

tuple1 = (1,2,3)
tuple2 = (1,2,4)
 
print (tuple1 == tuple2)    
 
print (tuple1 < tuple2)      
 
print (tuple1 > tuple2)

Output

False
True
False

How to convert string to a tuple in python

String to tuple conversion can be done as follows.

a = 'asdfghj'
b = tuple(i for i in a)
print(b)

Output

('a', 's', 'd', 'f', 'g', 'h', 'j')

How to convert a tuple to integer in python

A tuple is a group of heterogeneous elements, hence cannot be converted into a single data type.

How to copy a tuple in python

A tuple can be copied to another variable by using a simple = operator.

a = (1, 2, 3)
b = a
print(b)

Output

(1, 2, 3)

How to create a nested tuple in python

Nested tuples can be created by creating a tuple as an element inside a tuple.

a = (1, 2, 3, (1, 2))

How to create an empty tuple in python

An empty tuple is created by assigning a () to a variable.

a = ()

How to get input from user for tuple in python

Elements in a tuple can be read from the user as follows.

n = int(input())
b = tuple(input() for i in range(n))
print(b)

Output

4
1
d
3
1.3
('1', 'd', '3', '1.3')

How to pass tuple as argument in python

Tuples can be passed and returned as arguments by their variable names.

def tup(a):
    print(a)

a = (1,2)
tup(a)

Output

(1, 2)

How to remove an element from a tuple in python

As tuples are immutable, elements once added cannot be removed from a tuple.

How to save tuple in python

Once a tuple is created, it is saved by default in the memory of the system.

How to search a list of tuples in python

In a list of tuples, its elements can be searched and accessed by their respective indices.

 a = [(1,2),(3,4)]

print(a[1])
print(a[0])

Output

(3, 4)
(1, 2)

How to slice tuple in python

Tuples can be sliced using the slice operator (:) and a range of indices.

a = (1,2,3,4)

print(a[1:])

How to split tuple in python

Tuples can be split by assigning split parts to different variables.

a = (1,2,3,4)
b = a[1:]

print(b)

Output

(2, 3, 4)

How to store tuples in a list in python

Tuples can be treated as an element and can be stored in a list.

a = [(1, 2, 3), (4, 5)]

print(a[0])
print(a[1])

Output

(1, 2, 3)
(4, 5)

How to unzip tuples in python

Tuples in a list can be unzipped by using zip() keyword

zipped = [("x", 10), ("y", 20)]
unzipped_object = zip(*zipped)
unzipped_list = list(unzipped_object)
print(unzipped_list)

Output

[('x', 'y'), (10, 20)]

Is a tuple mutable in python

No, Tuples are immutable collections of elements.

What is a tuple object in python

Tuple objects are the elements in the tuple created. In the following example, the 2nd object in the tuple is printed.

a = (1 ,2, 3)
print(a[1])

Output

2

What is time tuple in python

Time tuple is a tuple that imports the current date and time from the datetime library.

import datetime
today = datetime.date.today()
time = today.timetuple()
print(time)
print(time.tm_year)

Output

time.struct_time(tm_year=2021, tm_mon=7, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=198, tm_isdst=-1)
2021

Which bracketing style does python use for tuples

Parenthesis () is used as a bracketing style for tuples.

What is a tuple of matrices python

A tuple of matrices is a tuple with a 2d array as its elements.

a  =([1,2,3], [4,5,6], [7,8,9])

for i in a:
    print(a)

Output

[1, 2, 3]
[4, 5, 6] 
[7, 8, 9]

Are python tuples ordered

Yes, python tuples are an ordered sequence of elements.

Are tuples faster than lists python

As tuples take less memory storage, they are faster than lists.

Are tuples in python passed by value

If you pass immutable arguments like integers, strings, or tuples to a function, the passing acts like a call-by-value. In the below code, the tuple is passed to the variable by value.

a = (1, 2, 3, 4)

Are tuples variables python

No, tuples are not variables but an ordered collection of objects.

Are tuples zero indexed in python

Yes, tuples are a collection that starts with an index of 0.

Can a function return a tuple in python

Yes, the return keyword is used to return a tuple by its variable.

def tup():
    a = (1,2,3,4)
    return(a)

print(tup())

Output

(1, 2, 3, 4)

Can a python tuple hold more than 1 type

Tuples can hold any number of values and types.

sample_tuple = (1, 2, "Python", False)

Can I add tuples as values to dictionary in python

 Yes, a tuple is a hashable value and can be used as dictionary keys.

hash = {('a','b','c'):(1,2,3)}
print(hash.keys())
print(hash.values())

Output

dict_keys([('a', 'b', 'c')])
dict_values([(1, 2, 3)])

Can I combine two lists into a tuple in python

Yes, lists can be combined into a tuple with a tuple keyword

a = (1,2,3)
b = (4,5,6)
c = tuple(a+b)
print(c)

Output

(1, 2, 3, 4, 5, 6)

Can I get rid of curly brackets in tuple in python

Curly brackets {} are used for sets and dictionaries and () for tuples. Eliminating () eliminates the scope of using a tuple.

Can I plot pairs of tuples in python

Tuple pairs are used in matplotlib library to denote (x, y) pairs in a graph.

Can I use split funtion on tuple in python

split() keyword is used to split strings into desired lengths but not tuples.

Can I reverse list of tuples in python

Tuples in a list can be reversed as follows.

a = [(1,2),(3,4)]
b = [a[::-1]]

print(b)

Output

[[(3, 4), (1, 2)]]

Can tuple hold mutable objects in python

Tuples can hold mutable objects like lists and arrays

a = ([1,2], 3, 'a')

print(a[1])

Output

[1, 2]


Can you de-tuple a two-word string in python

A string can be divided and passed into a tuple as follows.

a = 'tuplestring'
b = tuple(a[:])

print(b)

Output

('t', 'u', 'p', 'l', 'e', 's', 't', 'r', 'i', 'n', 'g')

Can you filter tuples in python

Yes, tuple elements can be filtered.

scores = (70, 60, 80, 90, 50)
filtered = filter(lambda score: score >= 70, scores)

print(list(filtered))

Output

[70, 80, 90]

Can you use 2 tuples in functions in python

def fun(a, b):
    print(a)
    print(b)

fun((1,2,4), (5,6))

Output

(1, 2, 4)
(5, 6)

Do you need quotation marks for tuple in python

Quotation marks are only used for char data type.

a = ('v', 'q')


Does empty tuple evaluate to false in python

Empty tuple returns false when cast to boolean

a = ()
b = bool(a)
print(b)

Output

False

Does python convert single element tuples to int

Yes, single element tuples can be converted into an integer

a = (1)
b = int(a)

print(type(b))

Output

<class 'int'>

Does python sort tuples by the first entry

No, but we can sort the tuple using the sort() method is used to sort the elements in ascending order and by default, it will sort the 1st element.

list1 = [('B', 1), ('D', 2), ('C', 3), ('A', 4)]
list1.sort()

print(list1)

Output

[('A', 4), ('B', 1), ('C', 3), ('D', 2)]

Does python support swap in tuples

Elements in a tuple cannot be swapped as tuples are immutable.

How do I separate nested tuple elements in python

Nested tuple elements can be separated by using their nested indices.

a = ((1, 2), (3, 4))
print(a[0][1])
print(a[1][1])

Output

2
4

How does heap sort in python sort same tuple values

If two tuples have the same first element then it will sort them according to the second element.

tuple_list = [(3,4), (4,3), (1,5), (5,1), (2,6), (6,2)]

a =  min(tuple_list, key=lambda x: x[1])
b = sorted(tuple_list, key=lambda x: x[1])
print(a)
print(b)

Output

(5, 1)
[(5, 1), (6, 2), (4, 3), (3, 4), (1, 5), (2, 6)]

How does set work on tuples in python

Sets can be treated as an element in tuple.

a = ({1, 2}, 3, 'a')

How to access indices of a tuple in python

Indices of tuple elements can be accessed by sort() method.

a = (1,2,3,4)
b = a.index(3)

print(b)

Output

2


How to access individual values, items, numbers or parts of a tuple in python

Individual tuple elements can be accessed by iterating through the entire tuple.

a = (1, 'a', 2.6)
for i in a:
    print(i)

Output

1
'a'
2.6

How to access second element of tuple in python

2nd element of a tuple can be accessed by using the index as 1.

a = (1, 2, 3, 4, 5)

print(a[1])

Output

2

How to flatten tuples in python

Lists in a tuple can be flattened as follows.

a = ([5, 6], [6, 7, 8, 9], [3])

print("The original tuple : " + str(a))

res = tuple(sum(a, []))

print("The flattened tuple : " + str(res))

Output

The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)

How to get length or shape of tuple in python

Length of a tuple can be found by using len() keyword.

a = (1, 2, 3, 4)
print(len(a))

Output

4

How to get max of a list of tuples in python

Maximum of a tuple can be found by using the keyword max().

a = (1, 2, 5)
print(max(a))

Output

5


How to loop through length of tuple in python

len() can be used in a loop to iterate through the length of a tuple.

a = (1, 2, 3, 4, 5)

for i in range(len(a)):
    print(i)

Output

1
2
3
4
5

How to make priority queue tuple in python

Priority queue is created by the use of a library PriorityQueue and the keyword put() as follows.

from queue import PriorityQueue

a = PriorityQueue()

a.put(4)
a.put(2)
a.put(5)
a.put(1)
a.put(3)

while not a.empty():
    b = a.get()
    print(b)

Output

1
2
3
4
5