Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between single asterisk and double asterisks before variable in python? [duplicate]

data = pd.read_csv("customers.csv")

print("Wholesale customers dataset has {} samples with {} features each."
      .format(*data.shape))

After this, I got the dimension numbers of the data. But I am wondering what is the usage of the asterisk before variable in Python.

like image 723
Cheung Riche Avatar asked Apr 30 '20 01:04

Cheung Riche


3 Answers

A single asterisk will take a tuple (or generally any iterator like a list) and expand it into a sequence of arguments, like so:

def multiply_two_numbers(x, y):
    return x * y


my_tuple = (3, 4)

multiply_two_numbers(my_tuple) # gives an error

multiply_two_numbers(*my_tuple) # gives 3 * 4 = 12

The double-asterisk does something similar, but with dictionaries instead, and with keyword arguments instead of positional arguments:

def say_my_name(first_name="", last_name=""):
    print(first_name + " " + last_name)


some_guy = {"first_name": "Homer", "last_name": "Simpson"}

say_my_name(**some_guy) # will print "Homer Simpson"
like image 89
Lagerbaer Avatar answered Oct 19 '22 00:10

Lagerbaer


Python has a very interesting way of dealing with function arguments (that I personally really like).
If we define a new function

def myFunc(*args, **kwargs):
    print(args, kwargs)

I can call the function with

myFunc(1, 2, 3, 4, a = 'a', b = 'b')

and get the output of

([1, 2, 3, 4], {'a': 'a', 'b': 'b'})

To specifcally answer your question, I can also call the function like this

myFunc(*[1, 2, 3, 4], **{'a': 'a', 'b': 'b'})

and get the exact same output
I can also use the asterisk to pass through positional arguments

def add(x, y):
   return x + y

and call it with

nums = [1, 2]
print(add(*nums))

stdout: 3
As you can see, the 1 and 2 are distributed amongst the function parameters.

TDLR

* unpacks a list into arguments, and ** unpacks a dictionary into keyword arguments
* and ** is the equivalent to ... in some other languages, if you want reference to that too.

like image 2
Luke-zhang-04 Avatar answered Oct 18 '22 23:10

Luke-zhang-04


People have got you covered for use in arguments, and stars often don't work in other contexts (see the end of this post).

But there is one other way you can use the stars and that is for variable unpacking.

>>> a, b, c = [1,2,3]
>>> print(a,b,c)
1 2 3

So, far, so good. But what if you only want to assign a for now? You can capture what's left in a starred variable.

a, *rest = [1,2,3]
>>> print (a, "and the rest", rest)
1 and the rest [2, 3]

An example of something that doesn't work:

>>> li = [1,2,3]
>>> var = *li
  File "<stdin>", line 1
SyntaxError: can't use starred expression here
like image 1
JL Peyret Avatar answered Oct 18 '22 22:10

JL Peyret