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

Why doesn't this create a list of tuples?

I'm not sure why this isn't creating a list of tuples like the assignment asks. When I try this in the python interpreter, it's returning a list of single characters in a strange order.

'''

combo('abc', 'def') ['a', 'd', 'a', 'e', 'a', 'f', 'b', 'd', 'b', 'e', 'b', 'f', 'c', 'd', 'c', 'e', 'c', 'f']

'''

Can someone please help me out?

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

def combo(iter1, iter2):
    tuple_list = []
    for i in iter1:
        for j in iter2:
            tuple_list += (i, j)

    return tuple_list

2 Answers

Steven Parker
Steven Parker
231,236 Points

The "+=" operator works like extend, not append.

So it separates your items first, then adds them to the list individually.

But just using append won't solve the whole issue because you have two loops instead of just one. So instead of just matching up the elements from both lists, you're creating a combination of each item from the first list with every item of the second.

Thank you! I was able to solve the problem. I used a for loop to count through a range of number as long as the list of one of the iterables. I then used the .append() method to add the tuple to the list.

Hara Gopal K
PLUS
Hara Gopal K
Courses Plus Student 10,027 Points

I accidentally did a very weird thing, is this the right way ? It seemed to have worked :D

def combo(one, two):
    output = []
    for a, b, in enumerate(one) and enumerate(two):    
        output.append(tuple([one[a], two[a]]))
    return output