Python Python Collections (2016, retired 2019) Tuples Combo

Md Akibe Hashan
Md Akibe Hashan
2,408 Points

Create a function named combo that takes two ordered iterables. These could be tuples, lists, s

can any one explain me how did this code working

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

def combo(*arg):
    my_result = []
    for index, val in enumerate(arg[0]):
        my_result.append((val, arg[1][index]))
    return my_result

1 Answer

Steven Parker
Steven Parker
203,717 Points

While this works, it's a rather unconventional and complicated solution. It's not necessary to use "enumerate" or the unpacking operator. What the solution above does can be simplified like this:

def combo(a, b):
    my_result = []
    for index in range(len(a)):
        my_result.append((a[index], b[index]))
    return my_result

With the extra complexity removed, the operation should be a bit more clear.

I'd guess you found this in an old question from 2017. You might want to see the even shorter solution I posted there. It also works the same way but uses list comprehension syntax to be more compact.