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

Anthony Lopez
Anthony Lopez
963 Points

Combo tuples

Hey guys,

I got this answer from searching some of the questions brought up around this challenge. I didn't see any answers that really explained what was going on here though, and I can't seem to understand what is actually happening on execution of this code.

Anyone able to break it down for me?

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

def combo(iterable1, iterable2):
    new_list = []
    for i in range(len(iterable1)):
        new_list.append((iterable1[i], iterable2[i]))
    return new_list

1 Answer

Jamaru Rodgers
Jamaru Rodgers
3,046 Points

Hey Anthony! Let me see if I can shed some light on whats going on here!

So when reading this functions, it will take two arguments in the parens which need to be iterables that we can loop through i.e. lists or strings.

Next, in the function's description, an empty list is created (new_list).

After the list's creation, a for loop is used to loop through a range of values, which is going to very depending on the length of the first iterable (iterable1) that was passed into our function as an argument. So, if our iterable1 is a list of 3 items, then the for loop is going to loop through the following code for a total of 3 times. This could have also been done without using range, but the code will still work!

For every item in this range, we are going to append a tuple data type to the empty list that we created above the loop. This new tuple will have two values (both of the iterables that were passed in as arguments to the function) and they are going to be at the same index as the item that we are currently on in the loop. So lets say the loop just started. Then, "i" is going to be 0 because our range goes from 0 to 2 (3 values). Since i = 0, the two iterable values in the tuple being added to the list will be whatever values are at the "zeroth" index of those iterables (which will be the first values).

Finally, once the loop is done adding these tuples to the list, the function then returns the new list back to the user!

lol I hope this helps!!

Anthony Lopez
Anthony Lopez
963 Points

Huge help Jamal! Thank you.