Literals: Literal
Literals: Literal
Python supports string and bytes literals and various numeric literals:
Evaluation of a literal yields an object of the given type (string, bytes, integer, floating
point number, complex number) with the given value. The value may be approximated
in the case of floating point and imaginary (complex) literals. See section Literals for
details.
All literals correspond to immutable data types, and hence the object’s identity is less
important than its value. Multiple evaluations of literals with the same value (either the
same occurrence in the program text or a different occurrence) may obtain the same
object or a different object with the same value.
A parenthesized expression list yields whatever that expression list yields: if the list
contains at least one comma, it yields a tuple; otherwise, it yields the single expression
that makes up the expression list.
An empty pair of parentheses yields an empty tuple object. Since tuples are immutable,
the same rules as for literals apply (i.e., two occurrences of the empty tuple may or may
not yield the same object).
Note that tuples are not formed by the parentheses, but rather by use of the comma
operator. The exception is the empty tuple, for which parentheses are required —
allowing unparenthesized “nothing” in expressions would cause ambiguities and allow
common typos to pass uncaught.
6.2.4. Displays for lists, sets and dictionaries
For constructing a list, a set or a dictionary Python provides special syntax called
“displays”, each of them in two flavors:
The comprehension consists of a single expression followed by at least one for clause
and zero or more for or if clauses. In this case, the elements of the new container are
those that would be produced by considering each of the for or if clauses a block,
nesting from left to right, and evaluating the expression to produce an element each
time the innermost block is reached.
However, aside from the iterable expression in the leftmost for clause, the
comprehension is executed in a separate implicitly nested scope. This ensures that
names assigned to in the target list don’t “leak” into the enclosing scope.
The iterable expression in the leftmost for clause is evaluated directly in the enclosing
scope and then passed as an argument to the implicitly nested scope. Subsequent for
clauses and any filter condition in the leftmost for clause cannot be evaluated in the
enclosing scope as they may depend on the values obtained from the leftmost iterable.
For example: [x*y for x in range(10) for y in range(x, x+10)].
Changed in version 3.8: yield and yield from prohibited in the implicitly nested
scope.