Page 308 - CTS - CSA TP - Volume 2
P. 308
COMPUTER SOFTWARE APPLICATION - CITS
Tuple Comprehensions:
1 Tuple comprehensions are similar to list comprehensions but create tuples instead. The syntax is the same as
for list comprehensions.
TASK 3: Squares of Numbers
Code:
tuple_of_squares = tuple(x**2 for x in range(1, 6))
print(“Tuple of squares:”, tuple_of_squares)
Explanation: This tuple comprehension creates a tuple of squares of numbers from 1 to 5.
Output :
TASK 4: Squares of even numbers from 1 to 10
Code:
# Generating a tuple of squares of even numbers from 1 to 10
even_squares = (x**2 for x in range(1, 11) if x % 2 == 0)
# Iterating over the tuple of even squares
for square in even_squares:
print(square)
Explanation :
• In this example, the generator expression (x**2 for x in range(1, 11) if x % 2 == 0) generates a tuple of squares
of even numbers from 1 to 10.
• When you need to iterate over the items of the tuple, you can use a for loop or convert the generator expression
into a tuple using the tuple() function:
• This approach is memory-efficient because it doesn’t create the entire tuple in memory at once. Instead, it
generates the items on-the-fly as needed.
• While tuple comprehensions don’t exist explicitly in Python, you can achieve similar functionality using
generator expressions to produce tuples.
293
CITS : IT & ITES - Computer Software Application - Exercise 135