Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
N element incremental tuples in Python
When it is required to create N element incremental tuples, generator expression and the tuple() method can be used. This technique creates tuples where each element is repeated N times in a sequence.
Example
The following example demonstrates creating tuples where each number from 1 to 5 is repeated 3 times ?
N = 3
print("The value of 'N' has been initialized")
print("The number of times it has to be repeated is:", N)
my_result = tuple((elem, ) * N for elem in range(1, 6))
print("The tuple sequence is:")
print(my_result)
The value of 'N' has been initialized The number of times it has to be repeated is: 3 The tuple sequence is: ((1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5))
How It Works
The expression (elem, ) * N creates a tuple with a single element repeated N times. The generator expression iterates through the range and creates these repeated tuples for each element.
Different Values of N
Let's see how different values of N affect the output ?
# N = 2
result_2 = tuple((elem, ) * 2 for elem in range(1, 4))
print("N=2:", result_2)
# N = 4
result_4 = tuple((elem, ) * 4 for elem in range(1, 4))
print("N=4:", result_4)
N=2: ((1, 1), (2, 2), (3, 3)) N=4: ((1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3))
Conclusion
Use generator expressions with tuple multiplication to create N element incremental tuples efficiently. The (elem, ) * N pattern repeats each element N times within individual tuples.
