Loop and Comprehension in tuple – Python

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.

# loop in tuple element one-by-one using for loop

shbytes_tuple = ('Python', 'AWS', 'Java', 'Azure', 'DataScience')

for element in shbytes_tuple:
    print(element)

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

Python
AWS
Java
Azure
Data Science

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.

# loop in tuple using element index within for loop

shbytes_tuple = ('Python', 'AWS', 'Java', 'Azure', 'DataScience')

for index in range(len(shbytes_tuple)):                           # using in-built range and len function
    print(shbytes_tuple[index])                                           # access element based on index

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

Python
AWS
Java
Azure
Data Science

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.

# loop in tuple using while loop

shbytes_tuple = ('Python', 'AWS', 'Java', 'Azure', 'DataScience')

index = 0
while index < len(shbytes_tuple):                           # using in-built len function
    print(shbytes_tuple[index])                                 # access element based on index
    index += 1                                                              # increase index by 1

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

Python
AWS
Java
Azure
Data Science

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.

# creating a new tuple using condition

shbytes_tuple = ('Python', 'AWS', 'Java', 'Azure', 'DataScience')
temp_list = []                   # Defined a new empty list

for element in shbytes_tuple:
  if "z" in element:                      # checking for condition
    temp_list.append(element)      # condition passed elements added to new list

new_shbytes_tuple = tuple(temp_list)    # new tuple is created from list
print(new_shbytes_tuple)                   # print elements in 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

('Azure',)

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.
  • iterableiterable 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

# creating a new tuple using tuple comprehension without if condition

shbytes_tuple = ('Python', 'AWS', 'Java', 'Azure', 'DataScience')

new_shbytes_tuple_4 = tuple(element for element in shbytes_tuple)
print(new_shbytes_tuple_4)

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

('Python', 'AWS', 'Java', 'Azure', 'DataScience')

From the output, new tuple has all elements as in iterated tuple.

Comprehension – New tuple with if condition

# creating a new tuple using tuple comprehension with if condition

shbytes_tuple = ('Python', 'AWS', 'Java', 'Azure', 'DataScience')

# creating a new tuple using tuple comprehension with if-in condition
print("creating a new tuple using tuple comprehension with if-in condition")
new_shbytes_tuple_2 = tuple(element for element in shbytes_tuple if "z" in element)
print(new_shbytes_tuple_2)

# creating a new tuple using tuple comprehension with if-not condition
print("creating a new tuple using tuple comprehension with if-not condition")
new_shbytes_tuple_3 = tuple(element for element in shbytes_tuple if element != "Java")
print(new_shbytes_tuple_3)

# creating a new tuple using tuple comprehension and range function
print("creating a new tuple using tuple comprehension and range function")
new_shbytes_tuple_5 = tuple(element for element in range(10) if element > 3)
print(new_shbytes_tuple_5)

Program Output

creating a new tuple using tuple comprehension with if-in condition
('Azure',)

creating a new tuple using tuple comprehension with if-not condition
('Python', 'AWS', 'Azure', 'DataScience')

creating a new tuple using tuple comprehension and range function
(4, 5, 6, 7, 8, 9)

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).

gen = (x**2 for x in range(5))
tuple_obj = tuple(gen)
print(tuple_obj)  # Elements in tuple_obj => (0, 1, 4, 9, 16)

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.
gen_expr = (x**2 for x in range(5))  # This creates a generator object
tuple_gen = tuple(gen_expr)  # tuple() converts generator to tuple
comprehension_list = [x**2 for x in range(5)]  # Comprehension directly creates a list

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.

tuple_obj = tuple((x, y) for x in range(2) for y in range(3))

# Elements in tuple => ((0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2))
print(tuple_obj)

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.

Q: What is the purpose of the enumerate() function when used with a tuple?

  • enumerate() function adds a counter to an iterable and returns it as an enumerate object
  • enumerate() object can be converted into a tuple of tuples containing pairs of index and value.
tuple_obj = ('a', 'b', 'c', 'd')
enumerated_tuple = tuple(enumerate(tuple_obj))
# Elements in enumerated tuple => ((0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'))

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *