Inserting tuple into a tuple

Viewed 182

I am using a loop to create tuples, and I would like to insert these tuples into a big tuple.

Assuming my input is (1, 2, 3), which is generated from every loop, my expected output is ((1, 2, 3), (1, 2, 3)).

I tried multiple ways but still cannot figure out how to do it.

big_tup = ()

for i in range(2):
    tup = (1, 2, 3)

    # this will cause AttributeError: 'tuple' object has no attribute 'insert'
    big_tup.insert(tup) 

    # this will combine all tuples together, output: (1, 2, 3, 1, 2, 3)
    big_tup += tup

    # this will make duplicates of (), output: (((), 1, 2, 3), 1, 2, 3)
    big_tup = (big_tup,) + tup

I would be very appreciated if anyone can help me solve this. Thanks in advance!

2 Answers

You don't want a tuple here; you want a list. Tuples are immutable; they can't be added to once they've been created.

Lists however can be appended to:

big_list = []
. . .
big_list.append(tup)

print(big_list)  # [(1, 2, 3), (1, 2, 3)]

As @carcigenicate pointed out here it is recommended to use list of tuples instead of tuple of tuples.

As seen here. You just need to use the below code if you are very particular to create a tuple of tuples.

big_tup = ()

for i in range(2):
    tup = (1, 2, 3)
    big_tup += (tup,) # this doesn't insert tup to big_tup, it is actually creating a new tuple and with the existing tuples and new tup using the same name

print(big_tup)
# ((1, 2, 3), (1, 2, 3))

See it in action here

Related