Home > Software engineering >  Unpacking arguments: how to stop a list from turning to a nested list
Unpacking arguments: how to stop a list from turning to a nested list

Time:11-28

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.

CodePudding user response:

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

CodePudding user response:

Ok, this is a weird problem with *args in that it returns (in this case) a tuple of args assigned to the variable name args. So, for example, given a function:

def test(*args):
    return args

It will return:

>>> test("Hello", "World")
('Hello', 'World')
>>> 

A tuple. Then, sorted, this gets turned into a list.

So, now we can go back and help the original problem, as the nested list comes as a result of the function "other_function" returning a list of 3 numbers, say [1,23,44], and the function is then applied to it.

>>> sorted(test([1,23,44]))
[[1, 23, 44]]
>>> 

NB: Tuples don't have a .sort method, instead an alternate method is to use the built in sorted() function.

  • Related