0

I have a simple question in python. How can I store arrays inside a tuple in Python. For example:

I want the output of my code to be like this:

bnds = ((0, 1), (0, 1), (0, 1), (0, 1))

So I want (0, 1) to be repeated for a specific number of times inside a tuple!

I have tried to use the following code to loop over a tuple:

g = (())
for i in range(4):
    b1 = (0,1) * (i)
    g = (g) + (b1)
print(g)

However, the output is :

(0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)

Maybe this is a simple question but I am still beginner in python!

Any help!

4 Answers4

0

You could create a list, fill it up, then convert it to a tuple.

g = []
b1 = (0, 1)

for i in range(4):
    g.append(b1)
g = tuple(g)
print(g)

There are cleaner ways to do it, but I wanted to adapt your code in order to help you understand what is happening.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
PythonForEver
  • 387
  • 2
  • 15
0

you can do this way

>>> result =tuple((0,1) for _ in range(4))
>>> result 
((0, 1), (0, 1), (0, 1), (0, 1))
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

A possible solution is this one:

g = tuple((0,1) for i in range(4))

-1

You can't change the items in tuple. Create g as a list then convert it into a tuple.

g = []
for i in range(4):
    b1 = (0,1) * (i)
    g .append(b1)
g = tuple(g)

Using list comprehension makes the code faster :

g = tuple([(0,1)*i for i in range(4)])

To get the output asked:

g = tuple([(0,1) for i in range(4)])
solac34
  • 156
  • 11