LittleBobbyTables
LittleBobbyTables

Reputation: 4473

Confusing double usage of python asterisk notation (as a function argument, or as a function definition)

I'm a bit confused. Let's create a function called x. I know that by putting * before the y, this means that we can add as many arguments as we want.

def x(*y):
    return y

However.

Case 1:

>>> x(1, 2)
(1, 2)

Case 2: Let's pass a list [1,2] with an asterisk before it:

>>> x(*[1,2])
(1, 2)

It seems that the single asterisk has two uses:

  1. For allowing multiple arguments in a function - essentially putting them into a list
  2. If done twice, to "break apart" a list into separate items

Why is this? Why can't I do something like: *a*b?

Upvotes: 2

Views: 273

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

In function definition * is used to collect all positional arguments in a tuple, in a function call * unpacks an iterable and passes it's items as positional arguments.

If by *a*b you're trying to unpack two iterables/iterators a and b then correct way is:

>>> a = [1, 2, 4]
>>> b = 'foo'
>>> from itertools import chain
def func(*x):
    print x
...     
>>> func(*chain(a,b)) #chain will work for both iterators and iterables
(1, 2, 4, 'f', 'o', 'o')

if both a and b are of same type and are iterable then you can also use :

>>> a = [1, 2, 4]
>>> b = [0,1]
>>> func(*(a + b))
(1, 2, 4, 0, 1)

Upvotes: 3

user2357112
user2357112

Reputation: 280207

Asterisks in a function definition are entirely separate from asterisks in a function call. You don't need two stars to break a list into separate arguments:

def f(a, b, c):
    return a*b + c

f(*(1, 2, 3)) # returns 5

In a definition, a starred argument receives any positional arguments that don't fit into the declared positional arguments, wrapped in a tuple. In a call, Python iterates over a starred argument and passes the elements as arguments individually. These features are sometimes useful together, but it's rare that you would define a function with a starred argument only to always pass it a starred argument.

Upvotes: 3

Related Questions