Looping is a process to repeat the similar task again and again. It provides sequential access to elements in the tuple.
Comprehension provides shorter syntax to iterate (loop) through tuple elements.
Follow quick-start guide, for all topics related to tuple in Python – Tuple in Python – Quickstart
To learn more about packing and unpacking of tuple, read our previous article – Packing & Unpacking of Tuple
Loop in Tuple
Loops are common to program workflow and are used with different types of collections like list, tuple, set, dictionary etc. Using loop we can iterate through the tuple elements and access each elements one-by-one.
There are multiple ways we can use loop to access the elements in tuple.
- For loop with tuple elements
- For loop with tuple using index
- While loop with tuple using index
- Create tuple in loop
- Create filtered tuple in loop with condition
For loop with tuple elements
Using for loop, we can iterate through the elements of a tuple.
We have defined a tuple ‘shbytes_tuple’. Using for loop we are accessing elements (one at a time) of a tuple and printing its value as an output.
Program Output
Elements in the tuple are printed as an output.
For loop with tuple using index
Using for loop, we can iterate through the index positions in a tuple.
In this program, we are using ‘range’ function with the length of tuple. Internally, range function will generate a sequence of numbers up-to length of tuple. Using for loop we will iterate through this sequence and will get index position element from the tuple.
Program Output
Elements in the tuple are printed as an output.
While loop with tuple using index
Using while loop also, we can iterate through the index positions in a tuple.
In this program, we are using a variable ‘index’, based on which we will iterate though the index positions. To get the next index position, increase ‘index’ variable by 1.
Program Output
Create filtered tuple in loop with condition
Tuple is an immutable datatype object. To create tuple based on filtered elements we need to use an mutable datatype like List.
We can iterate through the elements of a tuple, then we checked for the condition on each element. Elements which pass the given condition, add them into a temporary list. After the loop completed, we create a tuple from the temporary list. This will create a new filtered tuple.
We have created a tuple ‘shbytes_tuple’ (with 5 elements) and ‘temp_list’ (empty list). We are accessing elements of ‘shbytes_tuple’ using for loop and checking for if condition on each element. If element passed the condition, add that element into the ‘temp_list’. Once all the elements are checked and for loop is completed, then we create at tuple ‘new_shbytes_tuple’ using the temp_list elements.
Program Output
From the output, only element ‘Azure’ has ‘z’ in it from the given tuple elements.
Comprehension in tuple
- Comprehension provides shorter syntax to iterate (loop) through tuple elements.
- With comprehension, we can also use conditions to filter the elements.
- Comprehension also uses for loop
- We will use the tuple constructor to collect all elements as a tuple.
Comprehension syntax:
new_tuple = tuple(expression for item in iterable if condition == True)
expression
– This is the expression used to create the tuple element based on the item in current iteration. This expression can be a transformed based on the iterated item value.iterable
–iterable
can be any collection datatype that can be iterated over its elements. This can be a list, tuple, another dictionary etc.item in iterable
– This is the item in the current iteration in the iterable.if condition
– This is the condition based on which we can filter the iterated items.new_tuple
– This is the resulted new tuple with elements created from the comprehension
Let see the different ways we can use comprehension to create a new filtered tuple.
- Comprehension – New tuple without if condition
- Comprehension – New tuple with if condition
Comprehension – New tuple without if condition
With comprehension, for loop iterated through the elements in a tuple and returned the same element as an output. That element was collected with tuple constructor to create a new tuple.
Program Output
From the output, new tuple has all elements as in iterated tuple.
Comprehension – New tuple with if condition
Program Output
Summary
In this article we learned about Loop and Comprehension in tuple in Python. Following scenarios were explored:
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.
Python Topics
Interview Questions & Answers
Q: Can list comprehension be used to create a tuple?
No, list comprehensions directly produce lists and cannot be used to create tuples. However, similar result can be achieved using a generator expression combined with the tuple()
function => tuple_obj = tuple(x**2 for x in range(5))
Q: What is a generator expression, and how is it related to tuples?
Generator expression is similar to a list comprehension, but instead of creating a list, it returns a generator object that can be iterated over lazily (i.e., generating items one at a time as needed).
Here, gen
is the generator created using expression (x**2 for x in range(5))
. Using tuple()
constructor with gen
, we are creating a tuple object.
Q: What is the difference between a generator expression and a list comprehension when generating tuples?
- Generator expression, when used in place of a list comprehension, does not generate a tuple directly but instead produces a generator object.
- To convert it into a tuple, we have to pass the generator expression to the
tuple()
constructor. - List comprehensions generate lists directly, but the equivalent for a tuple must use a generator expression and conversion.
Q: How to perform a nested loop in a tuple comprehension?
Tuple comprehensions don’t exist. We can use a nested generator expression and then convert it to a tuple.
Q: How to create a tuple of tuples using a comprehension?
tuple_of_tuples = tuple((x, x**2) for x in range(6))
– This creates a tuple containing tuples where each sub-tuple consists of a number and its square.
enumerate()
function when used with a tuple?
Q: What is the purpose of the enumerate()
function adds a counter to an iterable and returns it as anenumerate
objectenumerate()
object can be converted into a tuple of tuples containing pairs of index and value.