FAQdash

Python FAQ question sets

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

First matching heading

Is there a source code-level debugger with breakpoints and single-stepping?

65 matching distinct questions. Reset filters

Questions by source file

Distinct questions by source fileSame counts as the adjacent table. Filtered sample only.General0Programming65Design and history0

Chart values

Denominator: 65 matching distinct questions
FileCount%
General00.0
Programming65100.0
Design and history00.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.

Programming / 65 matching questions

Complete retained English RST / PSF License v2

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

Is there a source code-level debugger with breakpoints and single-stepping?

Source occurrences: 1 / Link to question

[2] programming.rst L15-15
Read the retained source context

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

Is there a source code-level debugger with breakpoints and single-stepping?
---------------------------------------------------------------------------

Yes.

Several debuggers for Python are described below, and the built-in function
:func:`breakpoint` allows you to drop into any of them.

The pdb module is a simple but adequate console-mode debugger for Python. It is
part of the standard Python library, and is :mod:`documented in the Library
Reference Manual <pdb>`. You can also write your own debugger by using the code
for pdb as an example.

Are there tools to help find bugs or perform static analysis?

Source occurrences: 1 / Link to question

[2] programming.rst L54-54
Read the retained source context

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

Are there tools to help find bugs or perform static analysis?
-------------------------------------------------------------

Yes.

`Ruff <https://docs.astral.sh/ruff/>`__,
`Pylint <https://pylint.readthedocs.io/>`__ and
`Pyflakes <https://github.com/PyCQA/pyflakes>`__ do basic checking that will
help you catch bugs sooner.

Static type checkers such as `mypy <https://mypy-lang.org/>`__,
`ty <https://docs.astral.sh/ty/>`__,
`Pyrefly <https://pyrefly.org/>`__, and

How can I create a stand-alone binary from a Python script?

Source occurrences: 1 / Link to question

[2] programming.rst L73-73
Read the retained source context

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

How can I create a stand-alone binary from a Python script?
-----------------------------------------------------------

You don't need the ability to compile Python to C code if all you want is a
stand-alone program that users can download and run without having to install
the Python distribution first.  There are a number of tools that determine the
set of modules required by a program and bind these modules together with a
Python binary to produce a single executable.

One is to use the freeze tool, which is included in the Python source tree as
:source:`Tools/freeze`.
It converts Python byte code to C arrays; with a C compiler you can
embed all your modules into a new program, which is then linked with the

Are there coding standards or a style guide for Python programs?

Source occurrences: 1 / Link to question

[2] programming.rst L108-108
Read the retained source context

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

Are there coding standards or a style guide for Python programs?
----------------------------------------------------------------

Yes.  The coding style required for standard library modules is documented as
:pep:`8`.


Core language
=============

.. _faq-unboundlocalerror:

Why am I getting an UnboundLocalError when the variable has a value?

Why am I getting an UnboundLocalError when the variable has a value?

Source occurrences: 1 / Link to question

[2] programming.rst L120-120
Read the retained source context

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

Why am I getting an UnboundLocalError when the variable has a value?
--------------------------------------------------------------------

It can be a surprise to get the :exc:`UnboundLocalError` in previously working
code when it is modified by adding an assignment statement somewhere in
the body of a function.

This code:

   >>> x = 10
   >>> def bar():
   ...     print(x)
   ...

What are the rules for local and global variables in Python?

Source occurrences: 1 / Link to question

[2] programming.rst L193-193
Read the retained source context

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

What are the rules for local and global variables in Python?
------------------------------------------------------------

In Python, variables that are only referenced inside a function are implicitly
global.  If a variable is assigned a value anywhere within the function's body,
it's assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment's consideration explains this.  On
one hand, requiring :keyword:`global` for assigned variables provides a bar
against unintended side-effects.  On the other hand, if ``global`` was required
for all global references, you'd be using ``global`` all the time.  You'd have
to declare as global every reference to a built-in function or to a component of
an imported module.  This clutter would defeat the usefulness of the ``global``

Why do lambdas defined in a loop with different values all return the same result?

Source occurrences: 1 / Link to question

[2] programming.rst L209-209
Read the retained source context

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

Why do lambdas defined in a loop with different values all return the same result?
----------------------------------------------------------------------------------

Assume you use a for loop to define a few different lambdas (or even plain
functions), for example::

   >>> squares = []
   >>> for x in range(5):
   ...     squares.append(lambda: x**2)

This gives you a list that contains 5 lambdas that calculate ``x**2``.  You
might expect that, when called, they would return, respectively, ``0``, ``1``,
``4``, ``9``, and ``16``.  However, when you actually try you will see that

How do I share global variables across modules?

Source occurrences: 1 / Link to question

[2] programming.rst L261-261
Read the retained source context

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

How do I share global variables across modules?
------------------------------------------------

The canonical way to share information across modules within a single program is
to create a special module (often called config or cfg).  Just import the config
module in all modules of your application; the module then becomes available as
a global name.  Because there is only one instance of each module, any changes
made to the module object get reflected everywhere.  For example:

config.py::

   x = 0   # Default value of the 'x' configuration setting

What are the "best practices" for using import in a module?

Source occurrences: 1 / Link to question

[2] programming.rst L289-289
Read the retained source context

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

What are the "best practices" for using import in a module?
-----------------------------------------------------------

In general, don't use ``from modulename import *``.  Doing so clutters the
importer's namespace, and makes it much harder for linters to detect undefined
names.

Import modules at the top of a file.  Doing so makes it clear what other modules
your code requires and avoids questions of whether the module name is in scope.
Using one import per line makes it easy to add and delete module imports, but
using multiple imports per line uses less screen space.

It's good practice if you import modules in the following order:

Why are default values shared between objects?

Source occurrences: 1 / Link to question

[2] programming.rst L339-339
Read the retained source context

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

Why are default values shared between objects?
----------------------------------------------

This type of bug commonly bites neophyte programmers.  Consider this function::

   def foo(mydict={}):  # Danger: shared reference to one dict for all calls
       ... compute something ...
       mydict[key] = value
       return mydict

The first time you call this function, ``mydict`` contains a single item.  The
second time, ``mydict`` contains two items because when ``foo()`` begins
executing, ``mydict`` starts out with an item already in it.

How can I pass optional or keyword parameters from one function to another?

Source occurrences: 1 / Link to question

[2] programming.rst L395-395
Read the retained source context

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

How can I pass optional or keyword parameters from one function to another?
---------------------------------------------------------------------------

Collect the arguments using the ``*`` and ``**`` specifiers in the function's
parameter list; this gives you the positional arguments as a tuple and the
keyword arguments as a dictionary.  You can then pass these arguments when
calling another function by using ``*`` and ``**``::

   def f(x, *args, **kwargs):
       ...
       kwargs['width'] = '14.3c'
       ...
       g(x, *args, **kwargs)

What is the difference between arguments and parameters?

Source occurrences: 1 / Link to question

[2] programming.rst L416-416
Read the retained source context

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

What is the difference between arguments and parameters?
--------------------------------------------------------

:term:`Parameters <parameter>` are defined by the names that appear in a
function definition, whereas :term:`arguments <argument>` are the values
actually passed to a function when calling it.  Parameters define what
:term:`kind of arguments <parameter>` a function can accept.  For
example, given the function definition::

   def func(foo, bar=None, **kwargs):
       pass

*foo*, *bar* and *kwargs* are parameters of ``func``.  However, when calling

Why did changing list 'y' also change list 'x'?

Source occurrences: 1 / Link to question

[2] programming.rst L436-436
Read the retained source context

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

Why did changing list 'y' also change list 'x'?
------------------------------------------------

If you wrote code like::

   >>> x = []
   >>> y = x
   >>> y.append(10)
   >>> y
   [10]
   >>> x
   [10]

How do I write a function with output parameters (call by reference)?

Source occurrences: 1 / Link to question

[2] programming.rst L511-511
Read the retained source context

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

How do I write a function with output parameters (call by reference)?
---------------------------------------------------------------------

Remember that arguments are passed by assignment in Python.  Since assignment
just creates references to objects, there's no alias between an argument name in
the caller and callee, and consequently no call-by-reference.  You can achieve the
desired effect in a number of ways.

1) By returning a tuple of the results::

      >>> def func1(a, b):
      ...     a = 'new-value'        # a and b are local names
      ...     b = b + 1              # assigned to new objects

How do you make a higher order function in Python?

Source occurrences: 1 / Link to question

[2] programming.rst L578-578
Read the retained source context

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

How do you make a higher order function in Python?
--------------------------------------------------

You have two choices: you can use nested scopes or you can use callable objects.
For example, suppose you wanted to define ``linear(a,b)`` which returns a
function ``f(x)`` that computes the value ``a*x+b``.  Using nested scopes::

   def linear(a, b):
       def result(x):
           return a * x + b
       return result

Or using a callable object::

How do I copy an object in Python?

Source occurrences: 1 / Link to question

[2] programming.rst L637-637
Read the retained source context

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

How do I copy an object in Python?
----------------------------------

In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
Not all objects can be copied, but most can.

Some objects can be copied more easily.  Dictionaries have a :meth:`~dict.copy`
method::

   newdict = olddict.copy()

Sequences can be copied by slicing::

How can I find the methods or attributes of an object?

Source occurrences: 1 / Link to question

[2] programming.rst L653-653
Read the retained source context

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

How can I find the methods or attributes of an object?
------------------------------------------------------

For an instance ``x`` of a user-defined class, :func:`dir(x) <dir>` returns an alphabetized
list of the names containing the instance attributes and methods and attributes
defined by its class.


How can my code discover the name of an object?
-----------------------------------------------

Generally speaking, it can't, because objects don't really have names.
Essentially, assignment always binds a name to a value; the same is true of

How can my code discover the name of an object?

Source occurrences: 1 / Link to question

[2] programming.rst L661-661
Read the retained source context

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

How can my code discover the name of an object?
-----------------------------------------------

Generally speaking, it can't, because objects don't really have names.
Essentially, assignment always binds a name to a value; the same is true of
``def`` and ``class`` statements, but in that case the value is a
callable. Consider the following code::

   >>> class A:
   ...     pass
   ...
   >>> B = A
   >>> a = B()

What's up with the comma operator's precedence?

Source occurrences: 1 / Link to question

[2] programming.rst L702-702
Read the retained source context

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

What's up with the comma operator's precedence?
-----------------------------------------------

Comma is not an operator in Python.  Consider this session::

    >>> "a" in "b", "a"
    (False, 'a')

Since the comma is not an operator, but a separator between expressions the
above is evaluated as if you had entered::

    ("a" in "b"), "a"

Is there an equivalent of C's "?:" ternary operator?

Source occurrences: 1 / Link to question

[2] programming.rst L723-723
Read the retained source context

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

Is there an equivalent of C's "?:" ternary operator?
----------------------------------------------------

Yes, there is. The syntax is as follows::

   [on_true] if [expression] else [on_false]

   x, y = 50, 25
   small = x if x < y else y

Before this syntax was introduced in Python 2.5, a common idiom was to use
logical operators::

Is it possible to write obfuscated one-liners in Python?

Source occurrences: 1 / Link to question

[2] programming.rst L743-743
Read the retained source context

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

Is it possible to write obfuscated one-liners in Python?
--------------------------------------------------------

Yes.  Usually this is done by nesting :keyword:`lambda` within
:keyword:`!lambda`.  See the following three examples, slightly adapted from Ulf Bartelt::

   from functools import reduce

   # Primes < 1000
   print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
   map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))

   # First 10 Fibonacci numbers

What does the slash(/) in the parameter list of a function mean?

Source occurrences: 1 / Link to question

[2] programming.rst L778-778
Read the retained source context

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

What does the slash(/) in the parameter list of a function mean?
----------------------------------------------------------------

A slash in the argument list of a function denotes that the parameters prior to
it are positional-only.  Positional-only parameters are the ones without an
externally usable name.  Upon calling a function that accepts positional-only
parameters, arguments are mapped to parameters based solely on their position.
For example, :func:`divmod` is a function that accepts positional-only
parameters. Its documentation looks like this::

   >>> help(divmod)
   Help on built-in function divmod in module builtins:

How do I specify hexadecimal and octal integers?

Source occurrences: 1 / Link to question

[2] programming.rst L807-807
Read the retained source context

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

How do I specify hexadecimal and octal integers?
------------------------------------------------

To specify an octal digit, precede the octal value with a zero, and then a lower
or uppercase "o".  For example, to set the variable "a" to the octal value "10"
(8 in decimal), type::

   >>> a = 0o10
   >>> a
   8

Hexadecimal is just as easy.  Simply precede the hexadecimal number with a zero,
and then a lower or uppercase "x".  Hexadecimal digits can be specified in lower

Why does -22 // 10 return -3?

Source occurrences: 1 / Link to question

[2] programming.rst L830-830
Read the retained source context

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

Why does -22 // 10 return -3?
-----------------------------

It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
If you want that, and also want::

    i == (i // j) * j + (i % j)

then integer division has to return the floor.  C also requires that identity to
hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
the same sign as ``i``.

There are few real use cases for ``i % j`` when ``j`` is negative.  When ``j``

How do I get int literal attribute instead of SyntaxError?

Source occurrences: 1 / Link to question

[2] programming.rst L849-849
Read the retained source context

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

How do I get int literal attribute instead of SyntaxError?
----------------------------------------------------------

Trying to lookup an ``int`` literal attribute in the normal manner gives
a :exc:`SyntaxError` because the period is seen as a decimal point::

   >>> 1.__class__
     File "<stdin>", line 1
     1.__class__
      ^
   SyntaxError: invalid decimal literal

The solution is to separate the literal from the period

How do I convert a string to a number?

Source occurrences: 1 / Link to question

[2] programming.rst L870-870
Read the retained source context

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

How do I convert a string to a number?
--------------------------------------

For integers, use the built-in :func:`int` type constructor, for example, ``int('144')
== 144``.  Similarly, :func:`float` converts to a floating-point number,
for example, ``float('144') == 144.0``.

By default, these interpret the number as decimal, so that ``int('0144') ==
144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. ``int(string,
base)`` takes the base to convert from as a second optional argument, so ``int(
'0x144', 16) == 324``.  If the base is specified as 0, the number is interpreted
using Python's rules: a leading '0o' indicates octal, and '0x' indicates a hex
number.

How do I convert a number to a string?

Source occurrences: 1 / Link to question

[2] programming.rst L896-896
Read the retained source context

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

How do I convert a number to a string?
--------------------------------------

For example, to convert the number ``144`` to the string ``'144'``, use the built-in type
constructor :func:`str`.  If you want a hexadecimal or octal representation, use
the built-in functions :func:`hex` or :func:`oct`.  For fancy formatting, see
the :ref:`f-strings` and :ref:`formatstrings` sections.
For example, ``"{:04d}".format(144)`` yields
``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.


How do I modify a string in place?
----------------------------------

How do I modify a string in place?

Source occurrences: 1 / Link to question

[2] programming.rst L907-907
Read the retained source context

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

How do I modify a string in place?
----------------------------------

You can't, because strings are immutable.  In most situations, you should
simply construct a new string from the various parts you want to assemble
it from.  However, if you need an object with the ability to modify in-place
Unicode data, try using an :class:`io.StringIO` object or the :mod:`array`
module::

   >>> import io
   >>> s = "Hello, world"
   >>> sio = io.StringIO(s)
   >>> sio.getvalue()

How do I use strings to call functions/methods?

Source occurrences: 1 / Link to question

[2] programming.rst L939-939
Read the retained source context

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

How do I use strings to call functions/methods?
-----------------------------------------------

There are various techniques.

* The best is to use a dictionary that maps strings to functions.  The primary
  advantage of this technique is that the strings do not need to match the names
  of the functions.  This is also the primary technique used to emulate a case
  construct::

     def a():
         pass

Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines from strings?

Source occurrences: 1 / Link to question

[2] programming.rst L991-991
Read the retained source context

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

Is there an equivalent to Perl's ``chomp()`` for removing trailing newlines from strings?
-----------------------------------------------------------------------------------------

You can use ``S.rstrip("\r\n")`` to remove all occurrences of any line
terminator from the end of the string ``S`` without removing other trailing
whitespace.  If the string ``S`` represents more than one line, with several
empty lines at the end, the line terminators for all the blank lines will
be removed::

   >>> lines = ("line 1 \r\n"
   ...          "\r\n"
   ...          "\r\n")
   >>> lines.rstrip("\n\r")

Is there a ``scanf()`` or ``sscanf()`` equivalent?

Source occurrences: 1 / Link to question

[2] programming.rst L1010-1010
Read the retained source context

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

Is there a ``scanf()`` or ``sscanf()`` equivalent?
--------------------------------------------------

Not as such.

For simple input parsing, the easiest approach is usually to split the line into
whitespace-delimited words using the :meth:`~str.split` method of string objects
and then convert decimal strings to numeric values using :func:`int` or
:func:`float`.  :meth:`!split` supports an optional "sep" parameter which is useful
if the line uses something other than whitespace as a separator.

For more complicated input parsing, regular expressions are more powerful
than C's ``sscanf`` and better suited for the task.

What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?

Source occurrences: 1 / Link to question

[2] programming.rst L1025-1025
Read the retained source context

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

What does ``UnicodeDecodeError`` or ``UnicodeEncodeError`` error mean?
----------------------------------------------------------------------

See the :ref:`unicode-howto`.


.. _faq-programming-raw-string-backslash:

Can I end a raw string with an odd number of backslashes?
---------------------------------------------------------

A raw string ending with an odd number of backslashes will escape the string's quote::

Can I end a raw string with an odd number of backslashes?

Source occurrences: 1 / Link to question

[2] programming.rst L1033-1033
Read the retained source context

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

Can I end a raw string with an odd number of backslashes?
---------------------------------------------------------

A raw string ending with an odd number of backslashes will escape the string's quote::

   >>> r'C:\this\will\not\work\'
     File "<stdin>", line 1
       r'C:\this\will\not\work\'
       ^
   SyntaxError: unterminated string literal (detected at line 1)

There are several workarounds for this. One is to use regular strings and double
the backslashes::

My program is too slow. How do I speed it up?

Source occurrences: 1 / Link to question

[2] programming.rst L1075-1075
Read the retained source context

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

My program is too slow. How do I speed it up?
---------------------------------------------

That's a tough one, in general.  First, here is a list of things to
remember before diving further:

* Performance characteristics vary across Python implementations.  This FAQ
  focuses on :term:`CPython`.
* Behaviour can vary across operating systems, especially when talking about
  I/O or multi-threading.
* You should always find the hot spots in your program *before* attempting to
  optimize any code (see the :mod:`profile` module).
* Writing benchmark scripts will allow you to iterate quickly when searching

What is the most efficient way to concatenate many strings together?

Source occurrences: 1 / Link to question

[2] programming.rst L1134-1134
Read the retained source context

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

What is the most efficient way to concatenate many strings together?
--------------------------------------------------------------------

:class:`str` and :class:`bytes` objects are immutable, therefore concatenating
many strings together is inefficient as each concatenation creates a new
object.  In the general case, the total runtime cost is quadratic in the
total string length.  See :ref:`time-complexity` for more information.

To accumulate many :class:`str` objects, the recommended idiom is to place
them into a list and call :meth:`str.join` at the end::

   chunks = []
   for s in my_strings:

How do I convert between tuples and lists?

Source occurrences: 1 / Link to question

[2] programming.rst L1163-1163
Read the retained source context

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

How do I convert between tuples and lists?
------------------------------------------

The type constructor ``tuple(seq)`` converts any sequence (actually, any
iterable) into a tuple with the same items in the same order.

For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
yields ``('a', 'b', 'c')``.  If the argument is a tuple, it does not make a copy
but returns the same object, so it is cheap to call :func:`tuple` when you
aren't sure that an object is already a tuple.

The type constructor ``list(seq)`` converts any sequence or iterable into a list
with the same items in the same order.  For example, ``list((1, 2, 3))`` yields

What's a negative index?

Source occurrences: 1 / Link to question

[2] programming.rst L1180-1180
Read the retained source context

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

What's a negative index?
------------------------

Python sequences are indexed with positive numbers and negative numbers.  For
positive numbers 0 is the first index 1 is the second index and so forth.  For
negative indices -1 is the last index and -2 is the penultimate (next to last)
index and so forth.  Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.

Using negative indices can be very convenient.  For example ``S[:-1]`` is all of
the string except for its last character, which is useful for removing the
trailing newline from a string.

How do I iterate over a sequence in reverse order?

Source occurrences: 1 / Link to question

[2] programming.rst L1193-1193
Read the retained source context

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

How do I iterate over a sequence in reverse order?
--------------------------------------------------

Use the :func:`reversed` built-in function::

   for x in reversed(sequence):
       ...  # do something with x ...

This returns a reverse iterator without modifying your original sequence.


How do you remove duplicates from a list?
-----------------------------------------

How do you remove duplicates from a list?

Source occurrences: 1 / Link to question

[2] programming.rst L1204-1204
Read the retained source context

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

How do you remove duplicates from a list?
-----------------------------------------

See the Python Cookbook for a long discussion of many ways to do this:

   https://code.activestate.com/recipes/52560/

If you don't mind reordering the list, sort it and then scan from the end of the
list, deleting duplicates as you go::

   if mylist:
       mylist.sort()
       last = mylist[-1]

How do you remove multiple items from a list?

Source occurrences: 1 / Link to question

[2] programming.rst L1232-1232
Read the retained source context

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

How do you remove multiple items from a list?
---------------------------------------------

As with removing duplicates, explicitly iterating in reverse with a
delete condition is one possibility.  However, it is easier and faster
to use slice replacement with an implicit or explicit forward iteration.
Here are three variations::

   mylist[:] = filter(keep_function, mylist)
   mylist[:] = (x for x in mylist if keep_condition)
   mylist[:] = [x for x in mylist if keep_condition]

The list comprehension may be fastest.

How do you make an array in Python?

Source occurrences: 1 / Link to question

[2] programming.rst L1247-1247
Read the retained source context

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

How do you make an array in Python?
-----------------------------------

Use a list::

   ["this", 1, "is", "an", "array"]

Lists are equivalent to C or Pascal arrays in their time complexity; the primary
difference is that a Python list can contain objects of many different types.

The ``array`` module also provides methods for creating arrays of fixed types
with compact representations, but they are slower to index than lists.  Also
note that `NumPy <https://numpy.org/>`_

How do I create a multidimensional list?

Source occurrences: 1 / Link to question

[2] programming.rst L1275-1275
Read the retained source context

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

How do I create a multidimensional list?
----------------------------------------

You probably tried to make a multidimensional array like this::

   >>> A = [[None] * 2] * 3

This looks correct if you print it:

.. testsetup::

   A = [[None] * 2] * 3

How do I apply a method or function to a sequence of objects?

Source occurrences: 1 / Link to question

[2] programming.rst L1327-1327
Read the retained source context

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

How do I apply a method or function to a sequence of objects?
-------------------------------------------------------------

To call a method or function and accumulate the return values in a list,
a :term:`list comprehension` is an elegant solution::

   result = [obj.method() for obj in mylist]

   result = [function(obj) for obj in mylist]

To just run the method or function without saving the return values,
a plain :keyword:`for` loop will suffice::

Why does a_tuple[i] += ['item'] raise an exception when the addition works?

Source occurrences: 1 / Link to question

[2] programming.rst L1349-1349
Read the retained source context

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

Why does a_tuple[i] += ['item'] raise an exception when the addition works?
---------------------------------------------------------------------------

This is because of a combination of the fact that augmented assignment
operators are *assignment* operators, and the difference between mutable and
immutable objects in Python.

This discussion applies in general when augmented assignment operators are
applied to elements of a tuple that point to mutable objects, but we'll use
a ``list`` and ``+=`` as our exemplar.

If you wrote::

I want to do a complicated sort: can you do a Schwartzian Transform in Python?

Source occurrences: 1 / Link to question

[2] programming.rst L1436-1436
Read the retained source context

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

I want to do a complicated sort: can you do a Schwartzian Transform in Python?
------------------------------------------------------------------------------

The technique, attributed to Randal Schwartz of the Perl community, sorts the
elements of a list by a metric which maps each element to its "sort value". In
Python, use the ``key`` argument for the :meth:`list.sort` method::

   Isorted = L[:]
   Isorted.sort(key=lambda s: int(s[10:15]))


How can I sort one list by values from another list?
----------------------------------------------------

How can I sort one list by values from another list?

Source occurrences: 1 / Link to question

[2] programming.rst L1447-1447
Read the retained source context

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

How can I sort one list by values from another list?
----------------------------------------------------

Merge them into an iterator of tuples, sort the resulting list, and then pick
out the element you want.

   >>> list1 = ["what", "I'm", "sorting", "by"]
   >>> list2 = ["something", "else", "to", "sort"]
   >>> pairs = zip(list1, list2)
   >>> pairs = sorted(pairs)
   >>> pairs
   [("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
   >>> result = [x[1] for x in pairs]

What is a class?

Source occurrences: 1 / Link to question

[2] programming.rst L1467-1467
Read the retained source context

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

What is a class?
----------------

A class is the particular object type created by executing a class statement.
Class objects are used as templates to create instance objects, which embody
both the data (attributes) and code (methods) specific to a datatype.

A class can be based on one or more other classes, called its base class(es). It
then inherits the attributes and methods of its base classes. This allows an
object model to be successively refined by inheritance.  You might have a
generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
that handle various specific mailbox formats.

What is a method?

Source occurrences: 1 / Link to question

[2] programming.rst L1482-1482
Read the retained source context

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

What is a method?
-----------------

A method is a function on some object ``x`` that you normally call as
``x.name(arguments...)``.  Methods are defined as functions inside the class
definition::

   class C:
       def meth(self, arg):
           return arg * 2 + self.attribute


What is self?

What is self?

Source occurrences: 1 / Link to question

[2] programming.rst L1494-1494
Read the retained source context

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

What is self?
-------------

Self is merely a conventional name for the first argument of a method.  A method
defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
some instance ``x`` of the class in which the definition occurs; the called
method will think it is called as ``meth(x, a, b, c)``.

See also :ref:`why-self`.


How do I check if an object is an instance of a given class or of a subclass of it?
-----------------------------------------------------------------------------------

How do I check if an object is an instance of a given class or of a subclass of it?

Source occurrences: 1 / Link to question

[2] programming.rst L1505-1505
Read the retained source context

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

How do I check if an object is an instance of a given class or of a subclass of it?
-----------------------------------------------------------------------------------

Use the built-in function :func:`isinstance(obj, cls) <isinstance>`.  You can
check if an object
is an instance of any of a number of classes by providing a tuple instead of a
single class, for example, ``isinstance(obj, (class1, class2, ...))``, and can also
check whether an object is one of Python's built-in types, for example,
``isinstance(obj, str)`` or ``isinstance(obj, (int, float, complex))``.

Note that :func:`isinstance` also checks for virtual inheritance from an
:term:`abstract base class`.  So, the test will return ``True`` for a
registered class even if hasn't directly or indirectly inherited from it.  To

What is delegation?

Source occurrences: 1 / Link to question

[2] programming.rst L1579-1579
Read the retained source context

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

What is delegation?
-------------------

Delegation is an object-oriented technique (also called a design pattern).
Let's say you have an object ``x`` and want to change the behaviour of just one
of its methods.  You can create a new class that provides a new implementation
of the method you're interested in changing and delegates all other methods to
the corresponding method of ``x``.

Python programmers can easily implement delegation.  For example, the following
class implements a class that behaves like a file but converts all written data
to uppercase::

How do I call a method defined in a base class from a derived class that extends it?

Source occurrences: 1 / Link to question

[2] programming.rst L1633-1633
Read the retained source context

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

How do I call a method defined in a base class from a derived class that extends it?
------------------------------------------------------------------------------------

Use the built-in :func:`super` function::

   class Derived(Base):
       def meth(self):
           super().meth()  # calls Base.meth

In the example, :func:`super` will automatically determine the instance from
which it was called (the ``self`` value), look up the :term:`method resolution
order` (MRO) with ``type(self).__mro__``, and return a proxy that searches for
methods starting with the next class after ``Derived`` in the MRO: ``Base``.

How can I organize my code to make it easier to change the base class?

Source occurrences: 1 / Link to question

[2] programming.rst L1648-1648
Read the retained source context

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

How can I organize my code to make it easier to change the base class?
----------------------------------------------------------------------

You could assign the base class to an alias and derive from the alias.  Then all
you have to change is the value assigned to the alias.  Incidentally, this trick
is also handy if you want to decide dynamically (such as depending on availability
of resources) which base class to use.  Example::

   class Base:
       ...

   BaseAlias = Base

How do I create static class data and static class methods?

Source occurrences: 1 / Link to question

[2] programming.rst L1665-1665
Read the retained source context

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

How do I create static class data and static class methods?
-----------------------------------------------------------

Both static data and static methods (in the sense of C++ or Java) are supported
in Python.

For static data, simply define a class attribute.  To assign a new value to the
attribute, you have to explicitly use the class name in the assignment::

   class C:
       count = 0   # number of times C.__init__ called

       def __init__(self):

How can I overload constructors (or methods) in Python?

Source occurrences: 1 / Link to question

[2] programming.rst L1712-1712
Read the retained source context

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

How can I overload constructors (or methods) in Python?
-------------------------------------------------------

This answer actually applies to all methods, but the question usually comes up
first in the context of constructors.

In C++ you'd write:

.. code-block:: c++

    class C {
        C() { cout << "No arguments\n"; }
        C(int i) { cout << "Argument is " << i << "\n"; }

How do I get a list of all instances of a given class?

Source occurrences: 1 / Link to question

[2] programming.rst L1827-1827
Read the retained source context

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

How do I get a list of all instances of a given class?
------------------------------------------------------

Python does not keep track of all instances of a class (or of a built-in type).
You can program the class's constructor to keep track of all instances by
keeping a list of weak references to each instance.


Why does the result of ``id()`` appear to be not unique?
--------------------------------------------------------

The :func:`id` builtin returns an integer that is guaranteed to be unique during
the lifetime of the object.  Since in CPython, this is the object's memory

Why does the result of ``id()`` appear to be not unique?

Source occurrences: 1 / Link to question

[2] programming.rst L1835-1835
Read the retained source context

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

Why does the result of ``id()`` appear to be not unique?
--------------------------------------------------------

The :func:`id` builtin returns an integer that is guaranteed to be unique during
the lifetime of the object.  Since in CPython, this is the object's memory
address, it happens frequently that after an object is deleted from memory, the
next freshly created object is allocated at the same position in memory.  This
is illustrated by this example:

>>> id(1000) # doctest: +SKIP
13901272
>>> id(2000) # doctest: +SKIP
13901272

When can I rely on identity tests with the *is* operator?

Source occurrences: 1 / Link to question

[2] programming.rst L1863-1863
Read the retained source context

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

When can I rely on identity tests with the *is* operator?
---------------------------------------------------------

The ``is`` operator tests for object identity.  The test ``a is b`` is
equivalent to ``id(a) == id(b)``.

The most important property of an identity test is that an object is always
identical to itself, ``a is a`` always returns ``True``.  Identity tests are
usually faster than equality tests.  And unlike equality tests, identity tests
are guaranteed to return a boolean ``True`` or ``False``.

However, identity tests can *only* be substituted for equality tests when
object identity is assured.  Generally, there are three circumstances where

How can a subclass control what data is stored in an immutable instance?

Source occurrences: 1 / Link to question

[2] programming.rst L1952-1952
Read the retained source context

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

How can a subclass control what data is stored in an immutable instance?
------------------------------------------------------------------------

When subclassing an immutable type, override the :meth:`~object.__new__` method
instead of the :meth:`~object.__init__` method.  The latter only runs *after* an
instance is created, which is too late to alter data in an immutable
instance.

All of these immutable classes have a different signature than their
parent class:

.. testcode::

How do I cache method calls?

Source occurrences: 1 / Link to question

[2] programming.rst L2002-2002
Read the retained source context

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

How do I cache method calls?
----------------------------

The two principal tools for caching methods are
:deco:`functools.cached_property` and :deco:`functools.lru_cache`.  The
former stores results at the instance level and the latter at the class
level.

The ``cached_property`` approach only works with methods that do not take
any arguments.  It does not create a reference to the instance.  The
cached method result will be kept only as long as the instance is alive.

The advantage is that when an instance is no longer used, the cached

How do I create a .pyc file?

Source occurrences: 1 / Link to question

[2] programming.rst L2061-2061
Read the retained source context

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

How do I create a .pyc file?
----------------------------

When a module is imported for the first time (or when the source file has
changed since the current compiled file was created) a ``.pyc`` file containing
the compiled code should be created in a ``__pycache__`` subdirectory of the
directory containing the ``.py`` file.  The ``.pyc`` file will have a
filename that starts with the same name as the ``.py`` file, and ends with
``.pyc``, with a middle component that depends on the particular ``python``
binary that created it.  (See :pep:`3147` for details.)

One reason that a ``.pyc`` file may not be created is a permissions problem
with the directory containing the source file, meaning that the ``__pycache__``

How do I find the current module name?

Source occurrences: 1 / Link to question

[2] programming.rst L2111-2111
Read the retained source context

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

How do I find the current module name?
--------------------------------------

A module can find out its own module name by looking at the predefined global
variable ``__name__``.  If this has the value ``'__main__'``, the program is
running as a script.  Many modules that are usually used by importing them also
provide a command-line interface or a self-test, and only execute this code
after checking ``__name__``::

   def main():
       print('Running test...')
       ...

How can I have modules that mutually import each other?

Source occurrences: 1 / Link to question

[2] programming.rst L2128-2128
Read the retained source context

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

How can I have modules that mutually import each other?
-------------------------------------------------------

Suppose you have the following modules:

:file:`foo.py`::

   from bar import bar_var
   foo_var = 1

:file:`bar.py`::

   from foo import foo_var

__import__('x.y.z') returns <module 'x'>; how do I get z?

Source occurrences: 1 / Link to question

[2] programming.rst L2183-2183
Read the retained source context

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

__import__('x.y.z') returns <module 'x'>; how do I get z?
---------------------------------------------------------

Consider using the convenience function :func:`~importlib.import_module` from
:mod:`importlib` instead::

   z = importlib.import_module('x.y.z')


When I edit an imported module and reimport it, the changes don't show up.  Why does this happen?
-------------------------------------------------------------------------------------------------

For reasons of efficiency as well as consistency, Python only reads the module

When I edit an imported module and reimport it, the changes don't show up. Why does this happen?

Source occurrences: 1 / Link to question

[2] programming.rst L2192-2192
Read the retained source context

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

When I edit an imported module and reimport it, the changes don't show up.  Why does this happen?
-------------------------------------------------------------------------------------------------

For reasons of efficiency as well as consistency, Python only reads the module
file on the first time a module is imported.  If it didn't, in a program
consisting of many modules where each one imports the same basic module, the
basic module would be parsed and re-parsed many times.  To force re-reading of a
changed module, do this::

   import importlib
   import modname
   importlib.reload(modname)
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