Search code examples
pythonpython-3.xnestedtuples

How do I add a tuple to an existing one, and make it nested?


I'm new to coding.

The exercise is:

"The function gets 2 elements as parameters of the 'tuple' type. The function returns a tuple containing all of the pairs that can be created from the tuple elements, that have been sent as arguments.

Example:

first_tuple = (1, 2, 3)
second_tuple = (4, 5, 6)
mult_tuple(first_tuple, second_tuple)

Correct Result:

((1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 1), (5, 1), (6, 1), (4, 2), (5, 2), (6, 2), (4, 3), (5, 3), (6, 3))

This is my code:

def mult_tuple(tuple1, tuple2):
    new_tuple = ()

    for i in list(tuple1):
        for j in list(tuple2):
            temp_tuple = (i, j)
            new_tuple = new_tuple + (temp_tuple, )

    for i in list(tuple1):
        for j in list(tuple2):
            temp_tuple = (j, i)
            new_tuple = new_tuple + (temp_tuple, )

    return new_tuple

My question is, why only when I do: new_tuple = new_tuple + (temp_tuple, ) it returns the right result, and when I do: new_tuple = new_tuple + temp_tuple (With out the brackets on the temp_tuple), it returns an unested tuple?

Wrong result for example:

(1, 4, 1, 5, 1, 6, 2, 4, 2, 5, 2, 6, 3, 4, 3, 5, 3, 6, 4, 1, 5, 1, 6, 1, 4, 2, 5, 2, 6, 2, 4, 3, 5, 3, 6, 3)

Solution

  • In python when you use the + operator with two tuples, it appends the elements of the second tuple to the end of the first tuple.

    >>> ('a','b') + ('c','d')
    ('a', 'b', 'c', 'd')
    

    When you instead try to add (temp_tuple, ) to new_tuple, what you are actually doing is creating a new tuple with temp_tuple as its only element, so when you append this new tuple it is going to add its only element which is a tuple to the end of new_tuple.

    >>> ('a','b') + (('c','d'), )
    ('a', 'b', ('c', 'd'))
    

    In this example the second tuple only has ('c','d') as its only element, so it naturally gets added to the end of ('a', 'b').