Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Tuples Combo

Youssef Moustahib
Youssef Moustahib
7,779 Points

This worked, but how? I thought the () are not what makes the tuple?

I used this method to complete the question. But I'm not fully sure if I understood what I wrote. I used range and 'I' to assign an index position to 'i'. I then used x[i], y[I], this allowed me to looped through each utterable member in the variables x and y and assign them to the list.

But this where I don't understand:

Kenneth said that its the comma that makes the tuple? in the .append method in my code I wrapped what I wanted appended to the list in an extra parentheses so that they would count as one item as using one set of parentheses will only fail as it will think it is taking two arguments.

Actually, while writing this question I think I am understanding it lol. The first set of parentheses wanted an argument, the second set of parentheses enclosed x,y as a single argument, for instance end.append((5+6)). That would make a single argument. The comma between the x,y is what made the tuple in the argument.

Please comment and let me know if my chain of thought is correct.. slow but correct I hope lol

Thanks

combo.py
# combo([1, 2, 3], 'abc')
# Output:
# [(1, 'a'), (2, 'b'), (3, 'c')]

def combo(x,y):
    end = []

    for i in range(0, len(x)):
        end.append((x[i],y[i]))

    return end

1 Answer

andren
andren
28,558 Points

Your line of thinking is correct. Python has no way of distinguishing between a tuple being passed to a function and multiple arguments being passed when not enclosed in parenthesis.

While it is technically accurate that all that is needed to create a tuple is comma separated values, there are a lot of situations where your code will be ambiguous without using parenthesis. And the code you wrote is one such case.

If you had stored the tuple in a variable before trying to add it like this:

def combo(x,y):
    end = []
    for i in range(0, len(x)):
        combo_tuple = x[i], y[i]
        end.append(combo_tuple)
    return end

Then you would have been able to drop the extra parenthesis since there would no longer be any ambiguity.