proper name for python * operator?
In Ruby and Perl 6 this has been called "splat", and I think most people from
those communities will figure out what you mean if you call it that.
The Python tutorial uses the phrase "unpacking argument lists", which is
long and descriptive.
It is also referred to as iterable unpacking, or in the case of **
,
dictionary unpacking.
^=, -= and += symbols in Python
As almost any modern language, Python has assignment operators
so they can use them every time you want to assign a value to a variable after doing some arithmetic or logical operation, both (assignment and operation) are expressed in a compact way in one statement...
Table from Tutorials Point:
Operator Description Example = Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c += Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a -= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a *= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a /= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a %= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a **= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
The
*args
and**kwargs
is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.The
*args
will give you all function parameters as a tuple:def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3The
**kwargs
will give you all
keyword arguments except for those corresponding to a formal parameter as a dictionary.def bar(**kwargs):
for a in kwargs:
print(a, kwargs[a])
bar(name='one', age=27)
# name one
# age 27Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:
def foo(kind, *args, **kwargs):
passIt is also possible to use this the other way around:
def foo(a, b, c):
print(a, b, c)
obj = {'b':10, 'c':'lee'}
foo(100,**obj)
# 100 10 leeAnother usage of the
*l
idiom is to unpack argument lists when calling a function.def foo(bar, lee):
print(bar, lee)
l = [1,2]
foo(*l)
# 1 2In Python 3 it is possible to use
*l
on the left side of an assignment (Extended Iterable Unpacking), though it gives a list instead of a tuple in this context:first, *rest = [1,2,3,4]
first, *l, last = [1,2,3,4]Also Python 3 adds new semantic (refer PEP 3102):
def func(arg1, arg2, arg3, *, kwarg1, kwarg2):
passFor example the following works in python 3 but not python 2:
>>> x = [1, 2]
>>> [*x]
[1, 2]
>>> [*x, 3, 4]
[1, 2, 3, 4]
>>> x = {1:1, 2:2}
>>> x
{1: 1, 2: 2}
>>> {**x, 3:3, 4:4}
{1: 1, 2: 2, 3: 3, 4: 4}Such function accepts only 3 positional arguments, and everything after
*
can only be passed as keyword arguments.Note:
- A Python
dict
, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order.- "The order of elements in
**kwargs
now corresponds to the order in which keyword arguments were passed to the function." - What’s New In Python 3.6- In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.
What does - mean in Python function definitions?
It's a function annotation.
In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.
There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.
What does the asterisk do in Python other than multiplication and exponentiation?
Single asterisk in before a seqable object unpacks it, like Joran showed:
In [1]: def f(*args): return args
In [2]: f(1,2,3)
Out[2]: (1, 2, 3)
In [3]: f(*[1,2,3,4])
Out[3]: (1, 2, 3, 4)(Note a third application for
*
: in function definition an asterisk indicates a variable length list of arguments, all are being packed into one list,args
, inIn [1]
)Also worth noting is that a double asterisk (
**
) does a dictionary unpacking:In [5]: def g(foo=None, bar=42): return foo,bar
In [6]: g()
Out[6]: (None, 42)
In [7]: g(*[1,2])
Out[7]: (1, 2)
In [8]: g(**{'foo': 'FOO', 'bar': 'BAR'})
Out[8]: ('FOO', 'BAR')What does the at (@) symbol do in Python?
An
@
symbol at the beginning of a line is used for class and function decorators:
- PEP 318: Decorators
- Python Decorators
The most common Python decorators are:
@property
@classmethod
@staticmethod
An
@
in the middle of a line is probably matrix multiplication:
@
as a binary operator.Python integer incrementing with ++
Python doesn't support
++
, but you can do:number += 1
Behaviour of increment and decrement operators in Python
++
is not an operator. It is two+
operators. The+
operator is the identity operator, which does nothing. (Clarification: the+
and-
unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical++
operator to work on strings.)++count
Parses as
+(+count)
Which translates to
count
You have to use the slightly longer
+=
operator to do what you want to do:count += 1
I suspect the
++
and--
operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:
- Simpler parsing. Technically, parsing
++count
is ambiguous, as it could be+
,+
,count
(two unary+
operators) just as easily as it could be++
,count
(one unary++
operator). It's not a significant syntactic ambiguity, but it does exist.- Simpler language.
++
is nothing more than a synonym for+= 1
. It was a shorthand invented because C compilers were stupid and didn't know how to optimizea += 1
into theinc
instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.- Confusing side-effects. One common newbie error in languages with
++
operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.
Related Topics
How to Run Celery Workers by Superuser
Why Use Python's Os Module Methods Instead of Executing Shell Commands Directly
Unicodedecodeerror, Invalid Continuation Byte
Is There a Built-In Function to Print All the Current Properties and Values of an Object
Remove Duplicate Dict in List in Python
Split String on Whitespace in Python
How to Process Sigterm Signal Gracefully
Encrypt & Decrypt Using Pycrypto Aes 256
Is It Worth Using Python's Re.Compile
And' (Boolean) VS '&' (Bitwise) - Why Difference in Behavior with Lists VS Numpy Arrays
How to Round to 2 Decimals with Python
Copying Nested Lists in Python