Common Questions
This is a list of common questions within the Python tag. Each question includes some canonical SO questions that can be used to close-vote any new questions that match. If you have any suggestions then please come see us in chat.
- Each space separated value is a separate search term.
- Terms are ANDed together.
- [Brackets] indicate a tag term.
is:draft
shows only draft posts.is:community
shows only community posts.
Sometimes it is useful to access both the current and next item when iterating over a list. |
A mutable object is modified in a loop and appended to a list. The OP is surprised that all of the list items are duplicates of the last appended object. |
The asker does |
An |
Problems typically being solved by using a dispatch dict. |
Class attributes are shared across all instances of a class; especially when using mutable containers. |
The defaultdict requires a callable first argument, not the desired default value itself |
|
Generator expressions and list/set/dict comprehensions create a new scope that can’t see class variables. |
Users trying to put shell commands into the Python REPL will get NameError or SyntaxError exceptions. |
Create a single executable (exe) from a script, package, or other project. A common question when using Windows. |
Given a string |
Given a byte string, determine what charset should be used to decode it to text. |
Multiplying a list creates a shallow copy, not a deep copy, so any mutable objects in the list are then shared. Solution is to use a list comprehension to create separate objects. |
How do I create a variable with a given name? OR, how do I create a lot of numbered variables? Or, how should I add stuff to the |
Having a file with some |
The OP is surprised that attempting to access a file returned by |
Using |
Windows pathnames in source code with backslashes are fun. |
listdir() returns just the file names; you have to |
When you have multiple for loops, one nested in another, or you need a dynamic number of nested loops, use |
|
The asker is surprised that their |
The OP’s code attempts to use |
|
|
The user attempts to read/write global variables but does not correctly use the |
|
People get confused when |
How can I extract different parts of a string or list using slicing notation or the |
|
Unpacking assignment from a list, tuple, map, etc. into separate names |
Python cannot tell out of the box which character set your script uses, so you have to tell it. |
Specifying the type of items contained within a homogeneous list (or other collection) for the purpose of type hinting in PyCharm and other IDEs |
There are multiple installations of python, and neither |
Python 2 and 3 allow tabs to be used to indent lines. Python 2 will expand these to a multiple of 8, in Python 3 a tab can be equal only to another tab;, but many editors and Stack Overflow expand tabs to multiples of 4 instead. This can lead to subtle and weird flow errors. |
There is a broad array of possible indentation errors, and a broader array of fixes Examples: IndentationError: unexpected indent
IndentationError: expected an indented block
TabError: inconsistent use of tabs and spaces in indentation
SyntaxError (when connected to optional sections for compound statements broken by indentation errors)
|
The questioner’s |
With Python 3.x |
|
In Python 2, |
Browsers only send the values of inputs that have a |
Integer division (in Python 2.x) can cause issues for those unaware that |
|
256 is 256, 257 is not 257 |
|
Zip can be used to iterate over multiple lists at the same time. In Python 3.x a generator is used whilst in Python 2.x a new list of tuples is created, as such itertools.izip may be a better choice. |
The user dumps some data to JSON and renders it in a template, but the data contains HTML escape characters so it’s invalid JavaScript. |
main() function defined but never called |
Python throws an error if you modify the |
Make sure you are not name-clashing your modules |
The code has several |
“Astonishing” behaviour of default mutable arguments: |
Name-mangling in Python is one of the few ways to have “private” attributes. Note that within Python it is generally held that “we’re all consenting adults” and so there is no way to absolutely guarantee private attributes. |
A negative number raised to an even power returns a negative number due to the operator precedence. |
Usually, this means a function returned |
|
|
>>> 'value'
'value'
Shell or repr returns string with quotes. |
A single string or other object, possibly in parentheses, is passed as the second argument to |
|
WARNING : Python 2.4 eta post, doesn’t discuss |
Printing bytes still shows the |
Starting with Python 3.x print changed from a statement to a function. |
How to output |
Typical cause: attempting to |
It’s sometimes necessary to prompt the user for a response and check it, then re-prompt until it fulfils some test. |
The asker sees “unresolved reference” errors in PyCharm even though the library is installed. |
Division can sometimes trip up the new user, especially the difference between Python 2.x and 3.x. |
Someone using |
Tony the Pony…he comes… |
How to remove items from a list while iterating over the same list without skipping elements. |
Rendering a string directly results in an invalid JavaScript value. Need to use the |
Flask provides the |
How do you reverse a string? e.g. |
Why does id({}) == id({}) and id([]) == id([]) in CPython? |
Why do my variables disappear when I quit and restart? What format should I use for saving? |
A Pandas indexing how-to. |
The result set of a single column query is a list of tuples, instead of a list |
|
|
Sorting a list of version strings, eg |
How to split a single list into multiple lists with a fixed (maximum) size? |
People get surprised when str.strip treats the argument as a set of characters to remove. |
The caller gets a |
The questioner’s code runs a function and makes its return value a thread’s target instead of using the function as the target directly. |
Adding a trailing comma can cause problems, primarily the assignment of a tuple rather than the intended object. |
I have a |
An |
|