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,147 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).