How does swapping of members in tuples (a,b)=(b,a) work internally?

Python separates the right-hand side expression from the left-hand side assignment. First the right-hand side is evaluated, and the result is stored on the stack, and then the left-hand side names are assigned using opcodes that take values from the stack again. For tuple assignments with 2 or 3 items, Python just uses the stack … Read more

How is Python’s List Implemented?

The C code is pretty simple, actually. Expanding one macro and pruning some irrelevant comments, the basic structure is in listobject.h, which defines a list as: typedef struct { PyObject_HEAD Py_ssize_t ob_size; /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_item contains space for ‘allocated’ elements. The number … Read more

Python string interning

This is implementation-specific, but your interpreter is probably interning compile-time constants but not the results of run-time expressions. In what follows CPython 3.9.0+ is used. In the second example, the expression “strin”+”g” is evaluated at compile time, and is replaced with “string”. This makes the first two examples behave the same. If we examine the … Read more