Search code examples
pythonlistfunctionsortingargument-unpacking

Unpacking arguments: how to stop a list from turning to a nested list


I have created a function called other_func that results in a list, for example: [12,322,32]

I want to create a function that will receive the other function and it will sort this list. I want to use *args as seen below, to better understand how it works:

def biggest_gap(*args):
    result = sorted(args)
    return result

The issue is that it results in a nested list:

biggest_gap(other_func(3)) # The use of the other_func does not matter, only that it creates a list of numbers

[[322,32,12]]

If I use the sort() method:

def biggest_gap(*args):
        result = args.sort()
        return result

returns:

AttributeError: 'tuple' object has no attribute 'sort'

The question is how to stop the 'sorted' approach from creating a nested list and simply create a list or how to make the sort() method not throw an error.


Solution

  • def biggest_gap(*args):
    

    means that args will be a list (well, technically a tuple) of all arguments you gave to the biggest_gap function.

    biggest_gap(other_func(3))
    

    will give a list to the biggest_gap function. That's one argument.

    So what you get is "a tuple of (a list)".

    What you meant to do was giving a multiple individual arguments, by "splatting" the list returned from other_func:

    biggest_gap(*other_func(3))
    

    The difference the * makes is

    biggest_gap([322, 32, 12])    # without * - biggest_gap receives 1 argument
    biggest_gap(*[322, 32, 12])   # with * - biggest_gap receives 3 arguments
    biggest_gap(322, 32, 12)      # hard-coded equivalent
    

    See https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists