FAQdash

Python FAQ question sets

116 distinct English headings in three pinned files, not a measure of demand.

First matching heading

Why does Python use indentation for grouping of statements?

28 matching distinct questions. Reset filters

Questions by source file

Distinct questions by source fileSame counts as the adjacent table. Filtered sample only.General0Programming0Design and history28

Chart values

Denominator: 28 matching distinct questions
FileCount%
General00.0
Programming00.0
Design and history28100.0

One heading is one question. Categories follow source files, not inferred intent. Each question below has its own occurrence count.

Questions and source occurrences

English source headings are preserved, including RST markup. Counts refer to this snapshot only. Open a source to read the answer in context.

Design and history / 28 matching questions

Complete retained English RST / PSF License v2

Open full archived opening-page capture (not this question; local viewer) / Image provenance

Why does Python use indentation for grouping of statements?

Source occurrences: 1 / Link to question

[3] design.rst L11-11
Read the retained source context

English original, selected lines 11-23. Excerpt only; continue in the linked complete file.

Why does Python use indentation for grouping of statements?
-----------------------------------------------------------

Guido van Rossum believes that using indentation for grouping is extremely
elegant and contributes a lot to the clarity of the average Python program.
Most people learn to love this feature after a while.

Since there are no begin/end brackets there cannot be a disagreement between
grouping perceived by the parser and the human reader.  Occasionally C
programmers will encounter a fragment of code like this::

   if (x <= y)
           x++;

Why am I getting strange results with simple arithmetic operations?

Source occurrences: 1 / Link to question

[3] design.rst L48-48
Read the retained source context

English original, selected lines 48-60. Excerpt only; continue in the linked complete file.

Why am I getting strange results with simple arithmetic operations?
-------------------------------------------------------------------

See the next question.


Why are floating-point calculations so inaccurate?
--------------------------------------------------

Users are often surprised by results like this::

    >>> 1.2 - 1.0
    0.19999999999999996

Why are floating-point calculations so inaccurate?

Source occurrences: 1 / Link to question

[3] design.rst L54-54
Read the retained source context

English original, selected lines 54-66. Excerpt only; continue in the linked complete file.

Why are floating-point calculations so inaccurate?
--------------------------------------------------

Users are often surprised by results like this::

    >>> 1.2 - 1.0
    0.19999999999999996

and think it is a bug in Python.  It's not.  This has little to do with Python,
and much more to do with how the underlying platform handles floating-point
numbers.

The :class:`float` type in CPython uses a C ``double`` for storage.  A

Why are Python strings immutable?

Source occurrences: 1 / Link to question

[3] design.rst L95-95
Read the retained source context

English original, selected lines 95-107. Excerpt only; continue in the linked complete file.

Why are Python strings immutable?
---------------------------------

There are several advantages.

One is performance: knowing that a string is immutable means we can allocate
space for it at creation time, and the storage requirements are fixed and
unchanging.  This is also one of the reasons for the distinction between tuples
and lists.

Another advantage is that strings in Python are considered as "elemental" as
numbers.  No amount of activity will change the value 8 to anything else, and in
Python, no amount of activity will change the string "eight" to anything else.

Why must 'self' be used explicitly in method definitions and calls?

Source occurrences: 1 / Link to question

[3] design.rst L112-112
Read the retained source context

English original, selected lines 112-124. Excerpt only; continue in the linked complete file.

Why must 'self' be used explicitly in method definitions and calls?
-------------------------------------------------------------------

The idea was borrowed from Modula-3.  It turns out to be very useful, for a
variety of reasons.

First, it's more obvious that you are using a method or instance attribute
instead of a local variable.  Reading ``self.x`` or ``self.meth()`` makes it
absolutely clear that an instance variable or method is used even if you don't
know the class definition by heart.  In C++, you can sort of tell by the lack of
a local variable declaration (assuming globals are rare or easily recognizable)
-- but in Python, there are no local variable declarations, so you'd have to
look up the class definition to be sure.  Some C++ and Java coding standards

Why can't I use an assignment in an expression?

Source occurrences: 1 / Link to question

[3] design.rst L154-154
Read the retained source context

English original, selected lines 154-166. Excerpt only; continue in the linked complete file.

Why can't I use an assignment in an expression?
-----------------------------------------------

Starting in Python 3.8, you can!

Assignment expressions using the walrus operator ``:=`` assign a variable in an
expression::

   while chunk := fp.read(200):
      print(chunk)

See :pep:`572` for more information.

Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

Source occurrences: 1 / Link to question

[3] design.rst L169-169
Read the retained source context

English original, selected lines 169-181. Excerpt only; continue in the linked complete file.

Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
----------------------------------------------------------------------------------------------------------------

As Guido said:

    (a) For some operations, prefix notation just reads better than
    postfix -- prefix (and infix!) operations have a long tradition in
    mathematics which likes notations where the visuals help the
    mathematician thinking about a problem. Compare the easy with which we
    rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
    doing the same thing using a raw OO notation.

    (b) When I read code that says len(x) I *know* that it is asking for

Why is join() a string method instead of a list or tuple method?

Source occurrences: 1 / Link to question

[3] design.rst L193-193
Read the retained source context

English original, selected lines 193-205. Excerpt only; continue in the linked complete file.

Why is join() a string method instead of a list or tuple method?
----------------------------------------------------------------

Strings became much more like other standard types starting in Python 1.6, when
methods were added which give the same functionality that has always been
available using the functions of the string module.  Most of these new methods
have been widely accepted, but the one which appears to make some programmers
feel uncomfortable is::

   ", ".join(['1', '2', '4', '8', '16'])

which gives the result::

How fast are exceptions?

Source occurrences: 1 / Link to question

[3] design.rst L233-233
Read the retained source context

English original, selected lines 233-245. Excerpt only; continue in the linked complete file.

How fast are exceptions?
------------------------

A :keyword:`try`/:keyword:`except` block is extremely efficient if no exceptions
are raised.  Actually
catching an exception is expensive.  In versions of Python prior to 2.0 it was
common to use this idiom::

   try:
       value = mydict[key]
   except KeyError:
       mydict[key] = getvalue(key)
       value = mydict[key]

Why isn't there a switch or case statement in Python?

Source occurrences: 1 / Link to question

[3] design.rst L260-260
Read the retained source context

English original, selected lines 260-272. Excerpt only; continue in the linked complete file.

Why isn't there a switch or case statement in Python?
-----------------------------------------------------

In general, structured switch statements execute one block of code
when an expression has a particular value or set of values.
Since Python 3.10 one can easily match literal values, or constants
within a namespace, with a ``match ... case`` statement.
See :ref:`the specification <match>` and :ref:`the tutorial <tut-match>`
for more information about :keyword:`match` statements.
An older alternative is a sequence of ``if... elif... elif... else``.

For cases where you need to choose from a very large number of possibilities,
you can create a dictionary mapping case values to functions to call.  For

Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?

Source occurrences: 1 / Link to question

[3] design.rst L302-302
Read the retained source context

English original, selected lines 302-314. Excerpt only; continue in the linked complete file.

Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?
--------------------------------------------------------------------------------------------------------

Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for
each Python stack frame.  Also, extensions can call back into Python at almost
random moments.  Therefore, a complete threads implementation requires thread
support for C.

Answer 2: Fortunately, there is `Stackless Python <https://github.com/stackless-dev/stackless/wiki>`_,
which has a completely redesigned interpreter loop that avoids the C stack.


Why can't lambda expressions contain statements?

Why can't lambda expressions contain statements?

Source occurrences: 1 / Link to question

[3] design.rst L314-314
Read the retained source context

English original, selected lines 314-326. Excerpt only; continue in the linked complete file.

Why can't lambda expressions contain statements?
------------------------------------------------

Python lambda expressions cannot contain statements because Python's syntactic
framework can't handle statements nested inside expressions.  However, in
Python, this is not a serious problem.  Unlike lambda forms in other languages,
where they add functionality, Python lambdas are only a shorthand notation if
you're too lazy to define a function.

Functions are already first class objects in Python, and can be declared in a
local scope.  Therefore the only advantage of using a lambda instead of a
locally defined function is that you don't need to invent a name for the
function -- but that's just a local variable to which the function object (which

Can Python be compiled to machine code, C or some other language?

Source occurrences: 1 / Link to question

[3] design.rst L330-330
Read the retained source context

English original, selected lines 330-342. Excerpt only; continue in the linked complete file.

Can Python be compiled to machine code, C or some other language?
-----------------------------------------------------------------

`Cython <https://cython.org/>`_ compiles a modified version of Python with
optional annotations into C extensions.  `Nuitka <https://nuitka.net/>`_ is
an up-and-coming compiler of Python into C++ code, aiming to support the full
Python language.


How does Python manage memory?
------------------------------

The details of Python memory management depend on the implementation.  The

How does Python manage memory?

Source occurrences: 1 / Link to question

[3] design.rst L339-339
Read the retained source context

English original, selected lines 339-351. Excerpt only; continue in the linked complete file.

How does Python manage memory?
------------------------------

The details of Python memory management depend on the implementation.  The
standard implementation of Python, :term:`CPython`, uses reference counting to
detect inaccessible objects, and another mechanism to collect reference cycles,
periodically executing a cycle detection algorithm which looks for inaccessible
cycles and deletes the objects involved. The :mod:`gc` module provides functions
to perform a garbage collection, obtain debugging statistics, and tune the
collector's parameters.

Other implementations (such as `Jython <https://www.jython.org>`_ or
`PyPy <https://pypy.org>`_), however, can rely on a different mechanism

Why doesn't CPython use a more traditional garbage collection scheme?

Source occurrences: 1 / Link to question

[3] design.rst L377-377
Read the retained source context

English original, selected lines 377-389. Excerpt only; continue in the linked complete file.

Why doesn't CPython use a more traditional garbage collection scheme?
---------------------------------------------------------------------

For one thing, this is not a C standard feature and hence it's not portable.
(Yes, we know about the Boehm GC library.  It has bits of assembler code for
*most* common platforms, not for all of them, and although it is mostly
transparent, it isn't completely transparent; patches are required to get
Python to work with it.)

Traditional GC also becomes a problem when Python is embedded into other
applications.  While in a standalone Python it's fine to replace the standard
``malloc()`` and ``free()`` with versions provided by the GC library, an application
embedding Python may want to have its *own* substitute for ``malloc()`` and ``free()``,

Why isn't all memory freed when CPython exits?

Source occurrences: 1 / Link to question

[3] design.rst L394-394
Read the retained source context

English original, selected lines 394-406. Excerpt only; continue in the linked complete file.

Why isn't all memory freed when CPython exits?
----------------------------------------------

Objects referenced from the global namespaces of Python modules are not always
deallocated when Python exits.  This may happen if there are circular
references.  There are also certain bits of memory that are allocated by the C
library that are impossible to free (e.g. a tool like Purify will complain about
these).  Python is, however, aggressive about cleaning up memory on exit and
does try to destroy every single object.

If you want to force Python to delete certain things when Python exits, use the
:mod:`atexit` module to run a function that will force those deletions.

Why are there separate tuple and list data types?

Source occurrences: 1 / Link to question

[3] design.rst L408-408
Read the retained source context

English original, selected lines 408-420. Excerpt only; continue in the linked complete file.

Why are there separate tuple and list data types?
-------------------------------------------------

Lists and tuples, while similar in many respects, are generally used in
fundamentally different ways.  Tuples can be thought of as being similar to
Pascal ``records`` or C ``structs``; they're small collections of related data which may
be of different types which are operated on as a group.  For example, a
Cartesian coordinate is appropriately represented as a tuple of two or three
numbers.

Lists, on the other hand, are more like arrays in other languages.  They tend to
hold a varying number of objects all of which have the same type and which are
operated on one-by-one.  For example, :func:`os.listdir('.') <os.listdir>`

How are lists implemented in CPython?

Source occurrences: 1 / Link to question

[3] design.rst L434-434
Read the retained source context

English original, selected lines 434-446. Excerpt only; continue in the linked complete file.

How are lists implemented in CPython?
-------------------------------------

CPython's lists are really variable-length arrays, not Lisp-style linked lists.
The implementation uses a contiguous array of references to other objects, and
keeps a pointer to this array and the array's length in a list head structure.

This makes indexing a list ``a[i]`` an operation whose cost is independent of
the size of the list or the value of the index.

When items are appended or inserted, the array of references is resized.  Some
cleverness is applied to improve the performance of appending items repeatedly;
when the array must be grown, some extra space is allocated so the next few

How are dictionaries implemented in CPython?

Source occurrences: 1 / Link to question

[3] design.rst L454-454
Read the retained source context

English original, selected lines 454-466. Excerpt only; continue in the linked complete file.

How are dictionaries implemented in CPython?
--------------------------------------------

CPython's dictionaries are implemented as resizable hash tables.  Compared to
B-trees, this gives better performance for lookup (the most common operation by
far) under most circumstances, and the implementation is simpler.

Dictionaries work by computing a hash code for each key stored in the dictionary
using the :func:`hash` built-in function.  The hash code varies widely depending
on the key and a per-process seed; for example, ``'Python'`` could hash to
``-539294296`` while ``'python'``, a string that differs by a single bit, could hash
to ``1142331976``.  The hash code is then used to calculate a location in an
internal array where the value will be stored.  Assuming that you're storing

Why must dictionary keys be immutable?

Source occurrences: 1 / Link to question

[3] design.rst L473-473
Read the retained source context

English original, selected lines 473-485. Excerpt only; continue in the linked complete file.

Why must dictionary keys be immutable?
--------------------------------------

The hash table implementation of dictionaries uses a hash value calculated from
the key value to find the key.  If the key were a mutable object, its value
could change, and thus its hash could also change.  But since whoever changes
the key object can't tell that it was being used as a dictionary key, it can't
move the entry around in the dictionary.  Then, when you try to look up the same
object in the dictionary it won't be found because its hash value is different.
If you tried to look up the old value it wouldn't be found either, because the
value of the object found in that hash bin would be different.

If you want a dictionary indexed with a list, simply convert the list to a tuple

Why doesn't list.sort() return the sorted list?

Source occurrences: 1 / Link to question

[3] design.rst L556-556
Read the retained source context

English original, selected lines 556-568. Excerpt only; continue in the linked complete file.

Why doesn't list.sort() return the sorted list?
-----------------------------------------------

In situations where performance matters, making a copy of the list just to sort
it would be wasteful. Therefore, :meth:`list.sort` sorts the list in place. In
order to remind you of that fact, it does not return the sorted list.  This way,
you won't be fooled into accidentally overwriting a list when you need a sorted
copy but also need to keep the unsorted version around.

If you want to return a new list, use the built-in :func:`sorted` function
instead.  This function creates a new list from a provided iterable, sorts
it and returns it.  For example, here's how to iterate over the keys of a
dictionary in sorted order::

How do you specify and enforce an interface spec in Python?

Source occurrences: 1 / Link to question

[3] design.rst L574-574
Read the retained source context

English original, selected lines 574-586. Excerpt only; continue in the linked complete file.

How do you specify and enforce an interface spec in Python?
-----------------------------------------------------------

An interface specification for a module as provided by languages such as C++ and
Java describes the prototypes for the methods and functions of the module.  Many
feel that compile-time enforcement of interface specifications helps in the
construction of large programs.

Python 2.6 adds an :mod:`abc` module that lets you define Abstract Base Classes
(ABCs).  You can then use :func:`isinstance` and :func:`issubclass` to check
whether an instance or a class implements a particular ABC.  The
:mod:`collections.abc` module defines a set of useful ABCs such as
:class:`~collections.abc.Iterable`, :class:`~collections.abc.Container`, and

Why is there no goto?

Source occurrences: 1 / Link to question

[3] design.rst L615-615
Read the retained source context

English original, selected lines 615-627. Excerpt only; continue in the linked complete file.

Why is there no goto?
---------------------

In the 1970s people realized that unrestricted goto could lead
to messy "spaghetti" code that was hard to understand and revise.
In a high-level language, it is also unneeded as long as there
are ways to branch (in Python, with :keyword:`if` statements and :keyword:`or`,
:keyword:`and`, and :keyword:`if`/:keyword:`else` expressions) and loop (with :keyword:`while`
and :keyword:`for` statements, possibly containing :keyword:`continue` and :keyword:`break`).

One can also use exceptions to provide a "structured goto"
that works even across
function calls.  Many feel that exceptions can conveniently emulate all

Why can't raw strings (r-strings) end with a backslash?

Source occurrences: 1 / Link to question

[3] design.rst L645-645
Read the retained source context

English original, selected lines 645-657. Excerpt only; continue in the linked complete file.

Why can't raw strings (r-strings) end with a backslash?
-------------------------------------------------------

More precisely, they can't end with an odd number of backslashes: the unpaired
backslash at the end escapes the closing quote character, leaving an
unterminated string.

Raw strings were designed to ease creating input for processors (chiefly regular
expression engines) that want to do their own backslash escape processing. Such
processors consider an unmatched trailing backslash to be an error anyway, so
raw strings disallow that.  In return, they allow you to pass on the string
quote character by escaping it with a backslash.  These rules work well when
r-strings are used for their intended purpose.

Why doesn't Python have a "with" statement for attribute assignments?

Source occurrences: 1 / Link to question

[3] design.rst L671-671
Read the retained source context

English original, selected lines 671-683. Excerpt only; continue in the linked complete file.

Why doesn't Python have a "with" statement for attribute assignments?
---------------------------------------------------------------------

Python has a :keyword:`with` statement that wraps the execution of a block, calling code
on the entrance and exit from the block.  Some languages have a construct that
looks like this::

   with obj:
       a = 1               # equivalent to obj.a = 1
       total = total + 1   # obj.total = obj.total + 1

In Python, such a construct would be ambiguous.

Why don't generators support the with statement?

Source occurrences: 1 / Link to question

[3] design.rst L730-730
Read the retained source context

English original, selected lines 730-742. Excerpt only; continue in the linked complete file.

Why don't generators support the with statement?
------------------------------------------------

For technical reasons, a generator used directly as a context manager
would not work correctly.  When, as is most common, a generator is used as
an iterator run to completion, no closing is needed.  When it is, wrap
it as :func:`contextlib.closing(generator) <contextlib.closing>`
in the :keyword:`with` statement.


Why are colons required for the if/while/def/class statements?
--------------------------------------------------------------

Why are colons required for the if/while/def/class statements?

Source occurrences: 1 / Link to question

[3] design.rst L740-740
Read the retained source context

English original, selected lines 740-752. Excerpt only; continue in the linked complete file.

Why are colons required for the if/while/def/class statements?
--------------------------------------------------------------

The colon is required primarily to enhance readability (one of the results of
the experimental ABC language).  Consider this::

   if a == b
       print(a)

versus ::

   if a == b:
       print(a)

Why does Python allow commas at the end of lists and tuples?

Source occurrences: 1 / Link to question

[3] design.rst L762-762
Read the retained source context

English original, selected lines 762-774. Excerpt only; continue in the linked complete file.

Why does Python allow commas at the end of lists and tuples?
------------------------------------------------------------

Python lets you add a trailing comma at the end of lists, tuples, and
dictionaries::

   [1, 2, 3,]
   ('a', 'b', 'c',)
   d = {
       "A": [1, 5],
       "B": [6, 7],  # last trailing comma is optional but good style
   }
Three source files and sample headings
Source files, byte hashes and JSON
  1. [1] Doc/faq/general.rst

    Archived original bytes

    SHA256 032069d738fc8ef2cc907e1d79e2b19898978dab722cd30c108684a29cd1cf0e

  2. [2] Doc/faq/programming.rst

    Archived original bytes

    SHA256 4a0bc1b572f4772afd47938cb08a39e857907f2cf26f045323c17a0db7b3f39e

  3. [3] Doc/faq/design.rst

    Archived original bytes

    SHA256 65ba1d14ad1f245ff177a1a7758b77880e76a9d37337b577619fdebe65f083e6

  4. [4] LICENSE

    Archived original bytes

    SHA256 b0e25a78cffb43f4d92de8b61ccfa1f1f98ecbc22330b54b5251e7b6ba010231

Complete extracted JSON