San
San

Reputation: 23

Tuple of tuples

I'm new to Python. Below code works fine.

tup1 = ('A', 'B')
tup2 = ('C', 'D')
f = tup1, tup2
for i, j in f:
    print(i,j)

But is there is only one tuple in it. It will not work. Any reason why? Thanks in advance

tup1 = ('A', 'B')
f = tup1
for i, j in f:
    print(i,j)

I am expecting result like below. A B

Upvotes: 1

Views: 94

Answers (2)

aditpatel
aditpatel

Reputation: 63

The code you're writing in only works if there are two items for each index in tup1. For example, if this were to be the case:

    random1 = ('a','b')
    random2 = (3,4)
    tup1 = (random1, random2)
    f = tup1

And then if you used the same loop you had, it would spit out 'a' and 'b' and then 3 and 4. If you're intentions are to just spit out the contents in f, then the following code should do the trick:

    tup1 = ('A', 'B')
    f = tup1
    for i in f:
        print(i)

Upvotes: 0

rdas
rdas

Reputation: 21275

f = tup1

Does not create a tuple. Try this:

f  = (tup1,) # extra comma at the end

Full code:

tup1 = ('A', 'B')
f = (tup1,)
for i, j in f:
    print(i,j)

Output:

A B

Upvotes: 2

Related Questions