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 (Retired) Tuples Combo

Create a function named combo() that takes two iterables and returns a list of tuples: this code works but..

def combo(iter1, iter2):
    output = []
    for index, value in enumerate(iter1):
# I don't see where [index] is defined for iter2
# I suspect that iterating over iter2 is happening 
# just being inside the for loop
# is that where [index] is coming from also?
# by some association with iter1, being inside the loop? 
        output.append((value, iter2[index]))
    return output
x = combo([1, 2, 3], 'abc')
print(x)
Cheo R
Cheo R
37,150 Points

Remember that values can be retrieved by getting the index of a list.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

def show(lst): 
..   for index, value in enumerate(lst): 
..     print("Index: {}\tValue: {}".format(index, value)) 

 show(list1)
Index: 0    Value: 1
Index: 1    Value: 2
Index: 2    Value: 3

show(list2)
Index: 0    Value: a
Index: 1    Value: b
Index: 2    Value: c

Your code:

for index, value in enumerate(iter1):
    output.append((value, iter2[index]))

Is making a tuple of two values:

  • value found in the first list at position of index, given to you by enumerate
  • value from the second list, at the position of of index, where the index is given to you by enumerate.

Say the first list is longer than the second list:

list3 = [1, 2, 3, 4]

show(c)
Index: 0    Value: 1
Index: 1    Value: 2
Index: 2    Value: 3
Index: 3    Value: 4

What do you think will happen?

combo(list3, list2)
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 9, in combo
IndexError: list index out of range

It gives and IndexError because the second list does not have a value at that index.

Cheo, you gave a beautiful in-depth explanation that I will go through in detail. I think you answered my question right off. Are you saying that the index that is referenced here:

  • output.append((value, iter2[index]))
  • is actually the index from iter1
  • and that number is used to collaberate the two iterables?
  • cause if it is, that is very clever, and I wouldn't have thought of it on my own