I want to create this tuple:
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)
I tried with this
a=1,1,1
for i in range (2,10):
a=a,(i,i,i)
However it creates a tuple inside other tuple in each iteration.
Thank you
Method 1: Using For loop with append() method Here we will use the for loop along with the append() method. We will iterate through elements of the list and will add a tuple to the resulting list using the append() method.
Loop Through a TupleYou can loop through the tuple items by using a for loop.
Use enumerate() to Iterate Through a Python List. With Python's enumerate() method you can iterate through a list or tuple while accessing both the index and value of the iterable (list or tuple) object. Using enumerate is similar to combining a basic for loop and a for loop that iterates by index.
Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index [0] , the second item has index [1] etc.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With