3 ms·
#1 is in the Python Programming FAQ at https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x https://docs.python.org/3/faq/p
by eesmith 6y ago
#1 is in the Python Programming FAQ at https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x https://docs.python.org/3/faq/programming.html#why-did-chang... though not exactly the context you mentioned.
#2 is because multiprocessing forks, and each Python fork has a copy of the original environment, so that list isn't so much shared as copied into all forked subprocesses. This is not specifically a Python pitfall as it is generally true of any language which support forking.
#3 is in the same FAQ, at https://docs.python.org/3/faq/programming.html#what-is-the-most-efficient-way-to-concatenate-many-strings-together https://docs.python.org/3/faq/programming.html#what-is-the-m... . There is a special optimization in CPython which tries to work around this common issue.
Note that if at all possible you should use f-strings, as f"The value of the variable is {myvar} blahblah" is the fastest option if there are a fixed number of strings.
#4 is mentioned in the "PythonSpeed/PerformanceTips" document at https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_Variables https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loc... .
> The final speedup available to us for the non-map version of the for loop is to use local variables wherever possible. If the above loop is cast as a function, append and upper become local variables. Python accesses local variables much more efficiently than global variables.
- zepearl 6y agoThank you