Understanding Tuples in Python

Understanding Tuples in Python

7 mins read876 Views Comment
Updated on Feb 23, 2022 14:12 IST

In this guide, you will learn all about Tuples in Python: creating tuples, accessing tuple items, looping through a tuple, and other tuple operations with the help of examples.

2022_02_Tuples-in-Python.jpg

A tuple is a fixed-length, immutable sequence of arbitrary Python objects. Syntactically, tuples (pronounced either as “toople” or “tuhple,”) are written as a series of objects which are separated by commas and coded in parentheses. To make tuples in Python with one or more elements, you should use a comma after each element.

Table of Contents

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

Creating Tuples in Python

#Example 1: t = ()  # empty tuple
t = ()  # empty tuple
t1 = ('2')  # An integer!
T1 = ('2,')  # A tuple containing an integer
t2 = tuple('sequence')
t3 = ('peaches', 3.0+5j, [1, 22, 333])
print("t is of type", type(t))
print("t1 is of type", type(t1))
print("T1 is of type", type(T1))
print("t2 is", t2)
print("t3 is", t3)
 

As observed in the above example, the elements or values of a tuple can be of different data types. You should also note that, when creating a tuple with one element, it is important to use the trailing comma. Parentheses and commas matter in tuples. In the example above, tuple t2 doesn’t use a comma and therefore without the trailing comma, t2 is interpreted as a type string. Here are some important points related to tuples:

  • Just like strings, elements of tuples can be accessed by offset and they support all sorts of offset operations such as indexing, slicing, etc.
  • Tuples are immutable sequence date types like strings, and therefore do not support any in-place operations applied to lists
  • Tuples generally contain an heterogeneous sequence of elements and they support arbitrary nesting

Accessing Tuple Items

Just like strings and lists, tuples are accessed by offset and hence they support all the offset-based access operations such as slicing and indexing.

#Example 2: Accessing List Items
Tuple1 = ('Python', 3.0, 'Shiksha Online', 'Python Courses')
print(Tuple1[0])     #Python
print(Tuple1[2])     #Shiksha Online
print(Tuple1[-1])    #Python Courses
 

Add Tuple Items

A tuple is an immutable sequence type, which means that you cannot make changes to a given tuple in places. This is why methods like append, remove, etc, which try to modify the tuple will return an error. However, there are a few workarounds that you can implement.

Using + operator

#Example 3: Adding item to tuple using + 
Tuple1 = (1, 2, 3)
print("Original Tuple:", Tuple1)
Tuple2 = ('ABCD', 'WXYZ', 5, 6, 7)
 
Tuple1 = Tuple1 + Tuple2
print("Update version 1 of Tuple:", Tuple1)
 

You should remember that the + operator does not modify the existing tuple, it just creates a new type with the same name

Converting Tuple to List

You can convert the given tuple to a list using the built-in list() method, add a new item using append or other list methods, and then convert back the list to a tuple using the built-in tuple() method.

#Example 4: Converting a tuple to list
T1 = (10,50,20,9,40,25,60,30,1,56)
print("Original Tuple:", Tuple1)
L1 = list(T1)                    #converting tuple to list
print(L1)                 
L1.append('ABCD')
T1 = tuple(L1)                   #converting list to tuple
print("Update version1 of Tuple:", T1)
 

Removing Tuple Items

Since a tuple is immutable, you can specifically remove individual elements from a tuple. However, you can delete the entire tuple using del.

#Example 5: Deleting entire tuple using del
Tuple1 = (1, 2, 3)
print("Original Tuple:", Tuple1)
del Tuple1
#print(Tuple1) this line will raise an error as the tuple no longer exists
 

You can also use the same workaround that you used when adding an element to a list, that is, converting a tuple to a list and then performing the required operation and then converting it back to a list. You can use the same workaround here as well.

Looping Through a Tuple

Like I mentioned earlier, you can access the items of the tuple using their index (or offset). Therefore, you can traverse a tuple just like you do with a list.

Method 1: Using for loop

The most common way to traverse a tuple is using looping mechanisms, especially for loop. Here’s a simple example.

#Example 6: Looping through a tuple: for loop 
Tuple1 = (1,'ABC', 2, 'XYZ', 3, 'abc', 'XYZ')
for items in Tuple1:
  print(items)
 

This works well if you just want to read the elements of the list.

Method 2: Using while loop

You can use a while loop as well to traverse the tuple.

#Example 7: Looping through a tuple: while loop
Tuple1 = (1,'ABC', 2, 'XYZ', 3, 'abc', 'XYZ')
i = 0
while i < len(Tuple1):
  print(f'{i}: {Tuple1[i]}')
  i = i + 1
 

Method 3: Using Python enumerate() method

At times you might want to keep track of the index along with the element. In such cases, you can use the enumerate method to iterate any sequence type. The enumerate() method adds a counter to an iterable and returns an enumerate object. The main advantage of this technique is that you can convert enumerated objects to list or tuple using list() & tuple() respectively.

Syntax: enumerate(iterable, start), where iterable is the sequence type that we want to traverse and start is the number from where the enumerate starts counting. If omitted, the default value is 0.

#Example 8: Looping through a tuple: using enumerate() method
Tuple1 = (1,'ABC', 2, 'XYZ', 3, 'abc', 'XYZ')
for i, res in enumerate(Tuple1): 
    print (i,":",res)
 

Copy Tuple

You can make a copy of an existing tuple using the following methods.

#Example 9: Copying Tuple
actual_tuple = ('jam', 'Sam', 'ham', 'dam')
 
#Method 1: Copying by slicing
new_tup1 = actual_tuple[:]
print(new_tup1)
 
#Method 2: Copying using built-in function list
new_tup2 = list(actual_tuple)
print(new_tup2)
 
#Method 3: Copying using generic copy.copy()
import copy
new_tup3 = copy.copy(actual_tuple) 
print(new_tup3)
 

Join Tuple

We already learned that tuples can’t be modified in place. So methods like append, extend do not work. The only way you can join tuples is to use + operator.

#Example 10: Joining Tuples: Using + operator
T1 = ('jam', 'Sam')
T2 = ('ham', 'dam')
 
T3 = T1 + T2
print(T3)
 

List of Tuples

A list of tuples is nothing but a list with nested tuples in it. Let us explore how to create a list of tuples in Python in detail.

Creating List of Tuples in Python

Using list & tuple basic syntax

#Example 11: Creating List of Tuples: Simple way
list_of_tuples = [(1, 'jam'), (2, 'sam'), (3, 'bam'), (4, 'ham')]
print(list_of_tuples)
 

The example is straightforward.

Using zip() function

You can use zip() function to map the lists together to create a list of tuples. Firstly, the zip function returns a zip object, which is an iterator of tuples based on the values that you pass to it. Then you can use the built-in list() method to combine all the resulting tuples to a list of tuples.

#Example 12: Creating List of Tuples: Using zip()
list1 = [1, 2, 3, 4]
list2 = ['jam', 'Sam', 'ham', 'dam']
list_of_tuples = list(zip(list1, list2))
print(list_of_tuples)
 

Using List Comprehension with zip() & iter()

The logic here is that we are trying to provide a customized grouping of items of a list/tuple depending on the number of elements in the list/tuple. The syntax is as follows

[x for xin zip(*[iter(list)]*number)]

The x is the iterator to iterate the list, the zip function is used to get the single iterator object, which is tuples, and lastly, the iter() function iterates an element of an object at a time. The ‘number’ just specifies the number of elements that are to be clubbed into a single tuple from the given list. Here’s an example.

#Example 13: Creating List of Tuples: Using zip() & iter()
list1 = [1, 'jam', 2, 'sam', 3, 'bam', 4, 'ham']
list_of_tuples = [x for x in zip(*[iter(list1)]*2)]
print(list_of_tuples)
 

Using map() function

The map() function basically maps the iterable and applies a function that you pass as an argument to the map(). Here, the map function maps the input list into tuples and then you combine all these tuples to form a list using list() function.

#Example 14: Creating List of Tuples: Using map()
list1 = [['jam'], ['sam']]
list_of_tuples = list(map(tuple, list1))
print(list_of_tuples)
 

Tuple Methods

Tuples support the following built-in functions.

#Example 15: Tuple Methods
tuple1 = (1, 2, 3, 4, 5, 6)
tuple2 = ('a', 'b', 'c', 'd', 'e')
tuple3 = ('a', 'b', 'c', 'd', 'e')
 
#len(), returns total length of tuple
print("Length of tuple1:", len(tuple1))
 
#max() & min(), returns maximum & minimum item of tuple
print("Maximum of tuple1", max(tuple1))
print("Minimum of tuple2", min(tuple2))
 
Top Trending Tech Articles:
Career Opportunities after BTech Online Python Compiler What is Coding Queue Data Structure Top Programming Language Trending DevOps Tools Highest Paid IT Jobs Most In Demand IT Skills Networking Interview Questions Features of Java Basic Linux Commands Amazon Interview Questions

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio