Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create tuple with a loop in python

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

like image 443
HolyCrack Avatar asked Feb 17 '18 02:02

HolyCrack


People also ask

How do you create a tuple for a loop in Python?

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.

Can we loop tuple in Python?

Loop Through a TupleYou can loop through the tuple items by using a for loop.

How do you loop a tuple?

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.

Can tuples have repeats?

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.


2 Answers

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)   
like image 165
FatihAkici Avatar answered Sep 27 '22 23:09

FatihAkici


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

a = tuple((i,)*3 for i in range(1, 10))
like image 21
Olivier Melançon Avatar answered Sep 28 '22 00:09

Olivier Melançon