How to create tuple with a loop in python

itertools.repeat can also be used here:

>>> from itertools import repeat
>>> [tuple(repeat(i, 3)) for i in range(1, 10)]
[(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9)]

If you want the final result to be in a tuple of tuples instead of a list of tuples, you can wrap tuple again:

>>> tuple(tuple(repeat(i, 3)) for i in range(1, 10))
((1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9))

If I were to imitate something like this, I would have done it in the following way:

a = tuple((n,n,n) for n in range(1,10))
print(a)

#((1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9))

This is the most simple and pythonic way to do this specific job.


Use an extra comma in your tuples, and just join:

a = ((1,1,1),)
for i in range(2,10):
    a = a + ((i,i,i),)

Edit: Adapting juanpa.arrivillaga's comment, if you want to stick with a loop, this is the right solution:

a = [(1,1,1)]
for i in range (2,10):
    a.append((i,i,i))
a = tuple(a)   

In this case, you can create it without having to use a loop.

a = tuple((i,)*3 for i in range(1, 10))