Home python What do * (asterisk) and ** double asterisk mean in Python?

What do * (asterisk) and ** double asterisk mean in Python?

Author

Date

Category

For example, what does * (asterisk) do in the following code:

print (* min (p for p in counter.items () if p [1] == max_count))
print (* team, * coef)
seasons = [datetime (* args) for args in [
  (Y, 1, 1), # winter
  (Y, 3, 1), # spring
  (Y, 6, 1), # summer
  (Y, 9, 1), # autumn
  (Y, 12, 1) # winter
]]
def lcm (* args):
  "" "Least common multiple." ""
  return reduce (lambda a, b: a * b // gcd (a, b), args)
async def watchdog (loop, last_activity_time, timeout, func, * args):
  "Run * func (* args) * if more than * timeout * seconds since * last_activity_time *."
  while (loop.time () - last_activity_time ()) & lt; timeout:
    await asyncio.sleep (1)
  return func (* args)

and what the two ** asterisks do:

'{a:. {n} f}'. format (** vars ())
class A:
  def __init __ (self, a, ** kwargs):
    super () .__ init __ (** kwargs)

Answer 1, authority 100%

An asterisk in Python besides multiplication x * y (help ('*') ) and erections
to the power x ** y
(help ('**') )

used to denote zero or more of something.

For example, in the description of the function parameters:

def f (* args):
  print (args)

* means the function accepts zero or more arguments ,
which are available inside the function as a tuple args :

& gt; & gt; & gt; f (1, 'a')
(1, 'a')

For named parameters, use two
asterisks
:

def g (a, b, * args, name = 'default', ** kwargs):
  print (a, b, args, name, kwargs)

here g () takes two required arguments and an arbitrary (zero or more) number
other arguments:

& gt; & gt; & gt; g (1, b = 2, c = 3)
1 2 () default {'c': 3}

kwargs is a dictionary of optional arguments passed by name (c in this case). A
args is an empty () tuple, as additional positional
no arguments were passed.

After * , all parameters must be passed by name,
example :

def min_item (items, *, key = lambda x: x):
  ...

When invoked, if given, key must be specified by name:
min ([1,2, -3], key = abs) .

Taking an arbitrary number of arguments can be useful when
creating wrapper functions:

def my_print (* args, ** kwargs):
  flush = kwargs.pop ('flush', True) # flush unless overriden
  print (* args, flush = flush, ** kwargs)

With multiple inheritance
** kwargs
helps
implement the requirement of parameter compatibility for methods of base classes, since kwargs allows you to pass arbitrary named arguments.

You can see that the asterisk can also be used when calling
functions
:

L = [1, 2, 3]
s = "abc"
print (* L, * s) # iterable unpacking: print (1, 2, 3, 'a', 'b', 'c')
# - & gt; 1 2 3 a b c

arbitrary collections (iterable in general) L , s are unpacked and each of their elements is passed as a separate argument to the called function (print () ).

Can also be used with explicit assignment:

& gt; & gt; & gt; first, * middle, last = L
& gt; & gt; & gt; first, middle, last
(1, [2], 3)

in this case, the first and last arguments from the L list are unpacked into explicitly
given names (first , last ), and remainder zero or more
list items are placed in the middle .

The asterisk can also be used when specifying lists, tuples, sets, and
dictionaries in the source code using the appropriate syntax (tuple,
list, set
, and dictionary
displays
):

& gt; & gt; & gt; * range (4), 4
(0, 1, 2, 3, 4)
& gt; & gt; & gt; [* range (4), 4]
[0, 1, 2, 3, 4]
& gt; & gt; & gt; {* range (4), 4}
{0, 1, 2, 3, 4}
& gt; & gt; & gt; {'x': 1, ** {'y': 2}} # dictionary unpacking inside dictionary display
{'x': 1, 'y': 2}

A subtle point: a comma in Python creates a tuple – parentheses are only needed for
empty tuple () . Therefore, the first line is equivalent: (* range (4), 4) .

As with function calls, the asterisk unpacks the collection here and acts as if each element were passed separately to their respective constructors.

This way you can add two
dictionary
or custom mappings (Mapping ):

& gt; & gt; & gt; a = {'a': 1, 'b': 2}
& gt; & gt; & gt; b = {'a': 3, 'c': 0}
& gt; & gt; & gt; {** a, ** b}
{'a': 3, 'b': 2, 'c': 0}
& gt; & gt; & gt; {** b, ** a}
{'a': 1, 'c': 0, 'b': 2}

If there are duplicate keys, later values ​​win, as usual : {'a': 1, 'a': 3} == {'a': 3} .

Knowing what the asterisk does is helpful to explain how zip (* matrix) transpose square matrix or how to iterate over exactly n elements at a time: zip (* [iterator] * n) .

In addition to the specified values, an asterisk can be present in the name
file to create a template (wildcard), to
example
:

from pathlib import Path
print (* Path (). glob ('*. py'))
print (* Path (). glob ('** / *. py'))

The first print () prints space separated all (zero or more) filenames in the current directory with the extension .py . This (* .py ) syntax is popular because it is used on the command line (shell).
The second print () with two asterisks ('** / *. Py' ) prints the names of Python files in the entire directory tree (including subdirectories).

Regular
expressions

* means repeating zero or more times:

import re
if re.fullmatch (r'x * ', text):
  print ('the text is empty or contains only `x``)

multiplication of natural numbers n * m can be thought of as repeating addition (zero or more) times. Similarly, exponentiation n ** m can be thought of as repetition of multiplication:

2 * 3 == 2 + 2 + 2
 2 ** 3 == 2 * 2 * 2
[2] * 3 == [2, 2, 2]

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions