What is the meaning of the asterisk (*) operator?

16

In C this operator is used in variables of type pointers, but in Python I do not know which way, and what the reason to use, so what is the meaning of the operator (*) in the Python language?     

asked by anonymous 02.11.2016 / 23:46

2 answers

15

Like C, this operator is used for multiplication. It can even be used to multiply a string by a number.

In C the symbol is also used as operator to get the value indicated by a pointer and also serves to declare types that are pointers. Python has no (apparent) pointers, with no alternative.

Python uses it as a special syntax, not operator, in a parameter to indicate that that parameter can receive an indefinite amount of arguments. This is similar to what C uses for the printf() function, for example ( can be seen here ).

Understand the difference between parameter and argument .

Note that there can only be a single declared parameter so it must be the last positional declared in the function. Named parameters can come in any order, including those described below.

There is also ** where you can get the names of the arguments (if it is passed by name) and with the names you can get their values since the names are organized in a dictionary.

Example:

def funcao(*parametros):
    for parametro in parametros:
        print(parametro)

def funcao2(**parametros):
    for parametro in parametros:
        print(parametro)

funcao(1, 2, 3, 4, 5)
print()
funcao2(a = 2, b = 3)

See running on ideone .

    
02.11.2016 / 23:59
5

Splat

I mentioned this in another question about PHP . It is an operator that assumes that you will pass to the method or assignment a list of parameters.

For example:

def funcao1(a, b=None, c=None):
    print(a, b, c)

>>> funcao1([1, 2, 3])
[1, 2, 3] None None
>>> funcao1(*[1, 2, 3])
1 2 3

def funcao2(*a):
    print(a)

>>> funcao2([1, 2, 3])
([1, 2, 3],)
>>> funcao2(*[1, 2, 3])
(1, 2, 3)

Or:

>>> um, dois, *outros = [1, 2, 3, 4, 5]
>>> um
1
>>> dois
2
>>> outros
[3, 4, 5]

In these cases, as in other languages, the argument that defines a splat should always be the last in a list of arguments for a function or in a list of assignments.

    
02.11.2016 / 23:53