Python Python Collections (2016, retired 2019) Tuples Combo

Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

combo function challenge

My code only applies to only two arguments but I'm hoping my code's on the right track. Any advice? Thanks!

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

def combo(tuple1,tuple2):
    tuple_list=[]
    for i, letter in enumerate(tuple2,start=1):
        number=tuple1[i]
        finaltuple=(number,letter)
        tuple_list.append(finaltuple)
    return tuple_list    

1 Answer

Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

Thanks for pointing that out. I don't see a need to do that. But I'm wondering how to make this function work on more than two arguments.

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Web Development Techdegree Student 35,923 Points

Hi Leo,

To make the function work with an arbitrary number of inputs, you would change the function signature from something like:

def combo(itr1, itr2):

to something like:

def combo(*args):

Then inside the function you could do something like:

    new_list = []  # initialise a new list
    list_length = len(args[0])
    tuple_length = len(args)

    for i in range(list_length):
        new_tuple = []  # we need the tuple to start out as a list so we can mutate it
        for j in range(tuple_length):
            new_tuple.append(args[j][i])
        new_tuple = tuple(new_tuple) # now we make it a tuple like the question wants
        new_list.append(new_tuple)
    return new_list

You would use it like this:

>>> combo([1, 2, 3], 'cat', ('a', 'b', 'c')
[(1, 'c', 'a'), (2, 'a', 'b'), (3, 't', 'c')]

Hope that makes sense,

Happy coding

Alex