-2

Here is one easy math function in Jupyter using Python 3

def sum(*formulation):

    ans = 0

    for i in formulation:
        ans += i
    return ans

If I want to try this function, I write down like this:

sum(1,2,3,4)

The output will be

10

My question is what is * mean in sum(*formulation)?

Because if I don't use *, I get an error.

jayveesea
  • 2,886
  • 13
  • 25

3 Answers3

2

The "*" and then "**" notation are called "packing" and "unpacking". The main idea is that if you unpack objects, the they are removed from their list/dict and if you pack objects, then they are placed into a list/dict. For example,

x = [*[1,2,3],4]
print(x)

Here I have "unpacked" the [1,2,3] into the list for "x". Hence, x is now [1,2,3,4]. Here is another example,

d1 = {'x':7}
d2 = {'y':10}
d3 = {**d1,**d2}

Here I have dictionary "unpacked" the first two dictionaries into the third one. Here is another example:

def func(*args):
    print(args)

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

Here the 1,2,3,4,5 are not in a list, hence they will be "packed" into a list called args in the func.

Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15
1

That is called a starred expression. In the argument list of a function, this means that all other supplied positional arguments (that are not caught by preceding positional arguments) will be "packed" into the starred variable as a list.

So

def function(*arguments):
    print(arguments)
function(1, 2, 3)

will return

[1, 2, 3]

Note that it has different behaviour in other contexts in which it is usually used to "unpack" lists or other iterables. The Searchwords for that would be "starred", "packing" and "unpacking".

A good mnemonic for unpacking is that they remove the list brackets

a, b, c = *[1, 2, 3]  #equivalent to
a, b, c =   1, 2, 3  

And for packing like a regex wildcard

def function(*arguments):
    pass
def function(zero, or_, more, arguments):
    pass
head, *everything_in_between, tail = [1, 2, 3, 4, 5, 6]
Talon
  • 1,775
  • 1
  • 7
  • 15
-1

It means that the function takes zero or more arguments and the passed arguments would be collected in a list called formulation.

For example, when you call sum(1, 2, 3, 4), formation would end up being [1, 2, 3, 4].

Another similar but different usage of * that you might come across is when calling the function. Say you have a function defined as def add(a, b), and you have a list l = [1, 2], when you call add(*l) it means to unpack l and is equivalent to add(l[0], l[1]).

satoru
  • 31,822
  • 31
  • 91
  • 141