Python features sequence unpacking where multiple
expressions, each evaluating to something assignable (e.g.,
a variable or a writable property) are associated just as in
forming tuple literal; as a whole, the results are then put on
the left-hand side of the equal sign in an assignment
statement. This statement expects an iterable object on
the right-hand side of the equal sign to produce the same
number of values as the writable expressions on the left-
hand side; while iterating, the statement assigns each of
the values produced on the right to the corresponding
expression on the left.[97]
Python has a "string format" operator % that functions
analogously to printf format strings in the C language—e.g.
"spam=%s eggs=%d" % ("blah", 2) evaluates to "spam=blah
eggs=2". In Python 2.6+ and 3+, this operator was
supplemented by the format() method of the str class, e.g.,
"spam={0} eggs={1}".format("blah", 2). Python 3.6 added "f-
strings": spam = "blah"; eggs = 2; f'spam={spam} eggs=
{eggs}'.[98]
Strings in Python can be concatenated by "adding" them
(using the same operator as for adding integers and floats);
e.g., "spam" + "eggs" returns "spameggs". If strings contain
numbers, they are concatenated as strings rather than as
integers, e.g. "2" + "2" returns "22".
Python supports string literals in several ways:
Delimited by single or double quotation marks; single and
double quotation marks have equivalent functionality
(unlike in Unix shells, Perl, and Perl-influenced
languages). Both marks use the backslash (\) as an escape
character. String interpolation became available in
Python 3.6 as "formatted string literals".[98]
Triple-quoted, i.e., starting and ending with three single
or double quotation marks; this may span multiple lines
and function like here documents in shells, Perl, and
Ruby.
Raw string varieties, denoted by prefixing the string
literal with r. Escape sequences are not interpreted;
hence raw strings are useful where literal backslashes are
common, such as in regular expressions and Windows-
style paths. (Compare "@-quoting" in C#.)
Python has array index and array slicing expressions in lists,
which are written as a[key], a[start:stop] or
a[start:stop:step]. Indexes are zero-based, and negative
indexes are relative to the end. Slices take elements from
the start index up to, but not including, the stop index. The
(optional) third slice parameter, called step or stride, allows
elements to be skipped or reversed. Slice indexes may be
omitted—for example, a[:] returns a copy of the entire list.
Each element of a slice is a shallow copy.
In Python, a distinction between expressions and statements is rigidly enforced, in contrast
to languages such as Common Lisp, Scheme, or Ruby. This distinction leads to duplicating
some functionality, for example:
List comprehensions vs. for-loops
Conditional expressions vs. if blocks
The eval() vs. exec() built-in functions (in Python 2, exec is a
statement); the former function is for expressions, while
the latter is for statements
A statement cannot be part of an expression; because of this restriction, expressions such as
list and dict comprehensions (and lambda expressions) cannot contain statements. As a
particular case, an assignment statement such as a = 1 cannot be part of the conditional
expression of a conditional statement.
Typing
The standard type hierarchy in Python 3
Python uses duck typing, and it has typed objects but untyped variable names. Type
constraints are not checked at definition time; rather, operations on an object may fail at
usage time, indicating that the object is not of an appropriate type. Despite being
dynamically typed, Python is strongly typed, forbidding operations that are poorly defined
(e.g., adding a number and a string) rather than quietly attempting to interpret them.
Python allows programmers to define their own types using classes, most often for object-
oriented programming. New instances of classes are constructed by calling the class, for
example, SpamClass() or EggsClass()); the classes are instances of the metaclass type (which
is an instance of itself), thereby allowing metaprogramming and reflection.
Before version 3.0, Python had two kinds of classes, both using the same syntax: old-style
and new-style.[99] Current Python versions support the semantics of only the new style.
Python supports optional type annotations.[5][100] These annotations are not enforced by the
language, but may be used by external tools such as mypy to catch errors. Python includes a
module typing including several type names for type annotations.[101][102] Also, Mypy supports
a Python compiler called mypyc, which leverages type annotations for optimization.[103]
Type Mutability Description Syntax
examples
bool immutable Boolean True
value False
bytearray mutable Sequence of bytearray(b'
bytes Some ASCII')
bytearray(b"
Some ASCII")
bytearray([1
19, 105, 107,
105])
bytes immutable Sequence of b'Some
bytes ASCII'
b"Some
ASCII"
bytes([119,
105, 107,
105])
complex immutable Complex 3+2.7j
number with 3 + 2.7j
real and 5j
imaginary
parts
dict mutable Associative {'key1': 1.0, 3:
array (or False}
dictionary) {}
of key and
value pairs;
can contain
mixed types
(keys and
values); keys
must be a
hashable
type
[Link] immutable An ellipsis ...
Type placeholder Ellipsis
to be used as
an index in
NumPy
arrays
float immutable Double- 1.33333
precision
floating-
point
number. The
precision is
machine-
dependent,
but in
practice it is
generally
implemente
d as a 64-bit
IEEE 754
number with
53 bits of
frozenset immutable Unordered frozenset({4.
set, contains 0, 'string',
no True})
duplicates;
frozenset()
can contain
mixed types,
if hashable
int immutable Integer of 42
unlimited
magnitude[10
5]
list mutable List, can [4.0, 'string',
contain True]
mixed types []
[Link] immutable An object None
ype representing
the absence
of a value,
often called
null in other
languages
[Link] immutable A NotImpleme
plementedTy placeholder nted
pe that can be
returned
from
overloaded
operators to
indicate
unsupported
operand
types
range immutable An range(−1, 10)
immutable range(10, −5,
sequence of −2)
numbers,
commonly
used for
iterating a
specific
number of
times in for
loops[106]
set mutable Unordered {4.0, 'string',
set, contains True}
no set()
duplicates;
can contain
mixed types,
if hashable
str immutable A character 'Wikipedia'
string: "Wikipedia"
sequence of
"""Spanning
Unicode
codepoints multiple
lines"""
tuple immutable Tuple, can (4.0, 'string',
contain True)
mixed types ('single
element',)
()