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

Asked

Viewed 4,174 times

25

In C this operator is used in pointer type variables. However, in Python I don’t know which way, and why to use it. Therefore, what is the meaning of the operator (*) in the Python language?

  • This operator serves for multiplication.

4 answers

20


Just 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 an operator to pick up the value indicated by a pointer and also serves to declare types that are pointers. Python has no pointers (apparent), therefore there is no alternative.

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

Understand the difference between parameter and argument.

Note that there can only be one single parameter declared like this and it needs to be the last positional declared in the function. Nominal parameters can come in any order, including those described below.

There is also the ** where you can take the names of the arguments (if passed nominally) and with the names you can take 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)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 3

    It does not need to be the last parameter declared, but the last in an Arguments positional list. In fact, it can be the first parameter followed by several keyword Arguments.

  • @Pablopalaces is it? I think it is the only language that accepts this, is to ask to give problem.

  • 1

    It’s not no ;), in fact, it allows you to safely override method signatures, without the user (from your framework) getting confused with the superscripted signature and the original signature. Examples of valid Python signatures: (*args, **kw), (*args, a=100, **kw), (*, a=None), etc...

  • I won’t be able to find it now, but I’ve read the arguments that other languages used not to allow it. But if it works that way, okay, it’s written down for whoever’s going to use it, the credit is yours.

  • Then you show Guido, I have nothing to do with this story :p

  • Who denied could inform what is wrong.

  • So... I told you ;)

  • @Palaces is good like this?

  • and still left to speak of the case that the "*" appears isolated in the list of arguments of a function - type def foo(a, b, *, c, d): ... and also his role in the case of sequence assignment: a, b, *c, d = range(10)

  • It is also worth putting some examples of the use of the asterisk in calling for to functions - which is complementary but different from their use in statement function.

  • @jsbueno did not speak because I do not know this use :D

  • Can I top it off? (Has a 7 point answer accepted - strange to start another - but - you are the Boss)

  • @jsbueno you can do whatever you want :)

Show 8 more comments

9

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 else:

>>> 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 defining a splat should always be the last one in a function’s argument list or in a list of assignments.

  • 3

    Must be the last in an Arguments positional list.

4

The asterisk (*), in Python, it has several features. The first, and most common in most programming languages, is to multiply between numerical values.

resultado = 3 * 2  
print(resultado) # Imprime o valor 6.

In addition to multiplication between numbers, the asterisk can also be used to multiply a string - similar to the string method repeat() in some languages - or any other object that has the special method __mul__ implemented.

string = "bola" * 3
lista = [1, 2, 3] * 2
print(string) # Imprime a string "bolabolabola".
print(lista)  # Imprime a lista [1, 2, 3, 1, 2, 3]

The second function of the asterisk is argument list unpacking - such as lists, tuples or any other object that is iterable - in function call, where each element will be passed as argument to function parameters.

def func(a, b):
    print(a + b)

values = [7, 3, 5]
func(*values) # É o mesmo que fazer func(values[0], values[1], values[2]).

The third asterisk function is the inverse of the previous one: define, in the signature of a function, that a parameter can receive an unlimited amount of values as argument. In this case, the arguments will be packaged in a tuple and passed to the parameter.

def func(*values)
    print(values) # Imprime a tupla (1, 2, 3, 4, 5)

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

A very important detail that we should keep in mind is that any parameter after *args will be treated as "keyword-only". This means that they can only be used as "key-value" instead of positional arguments.

def func(*args, a, b): pass

func(1, 2, 3, a = 4, b = 5) # Funciona.
func(1, 2, 3, 4, 5)         # Não funciona pois é obrigatório nomear A e B.

There is also the operator (**), formed by two asterisks. This operator is used to perform powers and define in the signature of a function that a given parameter will receive keyword Arguments (translation: keyword arguments / named arguments).

In this case, within the function, the values will be stored inside a dictionary, and the names of the parameters that the user defined in the function call will be the keys of the same.

def func(**kwargs):
    print(kwargs) # Imprime o dicionário {"name": "Eduardo", "age": 32}

user_age = 2 ** 5 # O resultado disso será 2 elevado a 5 = 32
func(name = "Eduardo", age = user_age)

It is important to note that the parameter declared as KWARGS shall always be the last of the function. The reason for this is that, after the statement of the same, it would no longer be possible to know to which parameter a given argument belongs. Therefore, the code below would generate an error:

def func(a, b, **kwargs, c, d): pass

Below are all ways of using the *args and **kwargs in function:

def func1(a, b, c, d, *args): pass

def func2(a, b, *args, c, d): pass

def func3(a, b, c, d, **kwargs): pass

def func4(a, b, c, d, *args, **kwargs): pass

def func5(a, b, *args, c, d, **kwargs): pass

In addition, even in the function statement, it is possible to use the asterisk to force the appointment of one or more arguments in the function call, without the need to declare *args.

To do this, the asterisk must be placed separately, and all parameters in which you want them to be "keyword-only" shall be to the right of the asterisk.

def func(a, b, *, c, d): pass

func(2, 3, c = 10, d = 25) # Funciona.
func(2, 3, 10, 25)         # Não funciona pois é obrigatório nomear C e D.

-4

That operator is used in multiplications.

Ex:

A = 5
B = 7 
C = A*B

Browser other questions tagged

You are not signed in. Login or sign up in order to post.