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 stuck

Alright, this one can be tricky but I'm sure you can do it. Create a function named combo that takes two ordered iterables. These could be tuples, lists, strings, whatever. Your function should return a list of tuples. Each tuple should hold the first item in each iterable, then the second set, then the third, and so on. Assume the iterables will be the same length. Check the code below for an example. I knew my code is not correct but I do not know how to fix it. Any hints?

https://teamtreehouse.com/library/python-collections-2/tuples/combo

def combo(first,second):
    new_tuple = []
    for a in first:
        for b in second:
            new_tuple.append((a,b))

    return(list(new_tuple))

1 Answer

combo([1, 2, 3], 'abc') should return [(1, 'a'), (2, 'b'), (3, 'c')] (3 outcomes). Your code returns all possible combinations of [1, 2, 3] and ['a', 'b', 'c'] (3 * 3 = 9 outcomes). If you know the zip function, this is rather easy:

def combo(first, second):
    new_tuple = []
    for a, b in zip(first, second):
        new_tuple.append((a, b))
    return new_tuple

Or if you know list comprehension:

def combo(first, second):
    return [(x, y) for x, y in zip(first, second)]

Since new_tuple is already of list type, you don't need to wrap it with list().

If you are not familiar with zip(), you can run a for-loop controlled by the index numbers:

def combo(first,second):
    new_tuple = []
    # Get the length of the lists; doesn't matter which one, since they are equal.
    length = len(first)
    for i in range(length):
        new_tuple.append((first[i], second[i]))

    return new_tuple

STICK WITH THE LAST APPROACH, since you can't use zip() in this exercise. Something I've overlooked.

@Kip Yin This code challenge didn't apply to me. I only stubbled upon it while tying to solve another challenge but it was really insightful. I really like your approach. You are really helpful. Thumbs up.