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

Kristian Vrgoc
Kristian Vrgoc
3,046 Points

combo.py: 2 quick questions

Hey,

I have two quick questions(see attached code)

Kind regards

Kristian

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

def combo(item_1, item_2):
    list_of_tuples = []
    for index, value in enumerate(item_1):
        list_of_tuple.append((value, item_2[index]))    # Why do I need another pair of ()?
    return list_of_tuple                                # How does Python know that item_2[index] is the same index as in item_1?   

1 Answer

Cheo R
Cheo R
37,150 Points

I rewrote your code slightly for explanation.

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

def combo(iterable_1, iterable_2):
    list_of_tuples = []
    for index, value in enumerate(iterable_1):
        list_of_tuples.append((value, iterable_2[index]))    # Why do I need another pair of ()?
    return list_of_tuples                                   # How does Python know that iterable_2[index] is the same index as in iterable_1? 

Looks like the function combo takes two arguments which are both iteratable (list and string).

Both have indexes and values: iterable[index] equals some value.

# Why do I need another pair of ()?

list_of_tuple.append((value, iterable_2[index]))  

The output is expecting a list of tuples.

# Output: # [(1, 'a'), (2, 'b'), (3, 'c')]

The parenthesis makes sure you're appending them together as a tuple. Excluding the parenthesis raises and error (cannot append more than one item at a time but you can append a tuple that has two items in it).