Python | N elements of incremental tuples

Python Methods and Functions

Method # 1: Using an Expression Generator + tuple()
A combination of the above functions can be used to accomplish this task. In this we need to iterate over N using generator expression and tuple construct using tuple ().

# Python3 code to demonstrate how it works
# N incremental tuples
# Using generator expression + tuple

 
# initialize N

N = 3  

 
# print N

print ( "Number of times to repeat:" + str (N))

 
< code class = "comments"> # N incremental tuples
# Using generator expression + tuple

res = tuple ((ele,) * N for ele in range ( 1 , 6 ))

 
# print result

print ( "Tuple sequence:" + str (res))

Output:

 Nu mber of times to repeat: 3 Tuple sequence: ((1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5) ) 

Method # 2: Using repeat () + list comprehension
This task can also be accomplished using a combination the above functions. In this we use repeat () to repeat elements N times. Iteration is handled using a list comprehension.

# Python3 code to demonstrate how it works
# N incremental tuples
# Using generator expression + tuple

from itertools import repeat

 
# initialize N

N = 3  

  
# print N

print ( "Number of times to repeat:" + str (N))

  
# N incremental tuples
# Using generator expression + tuple

res = tuple ( tuple (repeat (ele, N)) for ele in range ( 1 , 6 ))

 
# print result

print ( "Tuple sequence:" + str (res))

Output:

 Number of times to repeat: 3 Tuple sequence: ((1, 1, 1), (2, 2, 2), (3, 3, 3 ), (4, 4, 4), (5, 5, 5)) 




Get Solution for free from DataCamp guru