Skip to content
Next Next commit
gh-142518: Document thread-safety guarantees of list operations
  • Loading branch information
lysnikolaou committed Dec 10, 2025
commit fd400f0a302c8797f161738cee8d624ed480b9c5
43 changes: 43 additions & 0 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1369,6 +1369,49 @@ Lists are mutable sequences, typically used to store collections of
homogeneous items (where the precise degree of similarity will vary by
application).

.. note::

Individual operations on :class:`list` instances such as
:meth:`~list.append`, :meth:`~list.pop`, ``lst[i] = x``, and ``x = lst[i]``
are atomic and will not corrupt the list or crash when called concurrently
from multiple threads:

.. code-block::
:class: good

# These operations are safe to call concurrently from multiple threads
lst.append(item) # atomically appends item
lst.pop() # atomically removes and returns last item
lst[i] = value # atomically replaces item at index i
item = lst[i] # atomically retrieves item at index i

One exception to this rule is :meth:`~list.extend`. Its atomicity
guarantees depend on the iterable being passed. When the iterable is
a :class:`list`, a :class:`tuple`, a :class:`set`, a :class:`frozenset`,
a :class:`dict` or a :ref:`dictionary view object <dict-views>`, the
operation is atomic. Otherwise, an iterator is created which can be
concurrently modified by another thread.

Operations that involve multiple accesses, as well as iteration, are not
atomic. For example, the following patterns are not thread-safe:

.. code-block::
:class: bad

# NOT atomic: read-modify-write
lst[i] = lst[i] + 1

# NOT atomic: check-then-act
if lst:
item = lst.pop()

# NOT thread-safe: iteration while modifying
for item in lst:
process(item) # another thread may modify lst

Consider external synchronization when sharing :class:`list` instances
across threads. See :ref:`freethreading-python-howto` for more information.

.. class:: list(iterable=(), /)

Lists may be constructed in several ways:
Expand Down
Loading