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.
  • 1 - 100 of 107

Sometimes it is useful to access both the current and next item when iterating over a list.

The asker does new_list = old_list and is surprised when changes to the old list are reflected in the new list. The fix is to copy the list in one of many ways.

Make sure you are not name-clashing your modules

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

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 s, what is the best way to count the occurences of the individual characters c in the 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 globals dict? And the inverse, given a string with a variable name, how do I get the variable?

Asker has an empty block (or a comment) in an if statement.
The fix is to use a pass statement

Having a file with some <START> and some <END> marker, extract all the content between those markers.

The OP has code that should be indented but isn’t.

When you have multiple for loops, one nested in another, or you need a dynamic number of nested loops, use itertools.product().

The asker is surprised that their for loop containing a return statement exits after one iteration

The OP’s code attempts to use for loops two or more times to re-read a file without rewinding it.

Python cannot tell out of the box which character set your script uses, so you have to tell it.
The error you get is SyntaxError: Non-ASCII character '\xe2' in file bla.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

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.

The questioner’s __getattribute__ includes self.something, triggering __getattribute__ again.

With Python 3.x raw_input was scrapped and input now always returns a string object.

input (Python 3.x) and raw_input (Python 2.x) return the variable as a string, this can confuse users when they expect their “number” to be a number.

In Python 2, input treats strings as variable names and raises a NameError.

Browsers only send the values of inputs that have a name attribute.

Integer division (in Python 2.x) can cause issues for those unaware that 1/2 != 0.5

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

“Astonishing” behaviour of default mutable arguments: def cabbage(leaves=[]).

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 None where you expected it to return an object of some sort.

>>> '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 execute().

WARNING : Python 2.4 eta post, doesn’t discuss str.format

Printing bytes still shows the b prefix, escapes, and doesn’t break on newlines.

Starting with Python 3.x print changed from a statement to a function.

How to output Value is "42", yet print 'Value is: "', 42, '"', or print('Value is: "', 42, '")' adds extra spaces around 42

Typical cause: attempting to join() before performing get() on cross-process queues.

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 requests or urllib.client or urllib2, etc. is trying to load a URL but they get a different result from what their browser shows. Either because they get an HTTP error (404, 500, etc.) or different content from what they expected.

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 |tojson filter.

Flask provides the jsonify method to convert data into a JSON response.

How do you reverse a string? e.g. "foobar"[::-1]

Why does id({}) == id({}) and id([]) == id([]) in CPython?

A Pandas indexing how-to.

The result set of a single column query is a list of tuples, instead of a list
of values.

Sorting a list of version strings, eg ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"], into natural order.

How to split a single list into multiple lists with a fixed (maximum) size?

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 list of n-many objects - why does list.index(0) raise a ValueError and not return the first item?

You get this error when you try to call X() when X isn’t a function, method, or class.

When inside a Jinja expression, you reference the variables directly, rather than within nested curly braces.

When using str.join a list comprehension (rather than a generator expression) provides a significant speed boost

The splat operator (*) can be used to unpack variables from a container when calling a function.

From Python 3 onwards reduce must be imported from functools.

% can be used in string formatting. Note that it is now recommended to use the new str.format() syntax.

Choosing elements from a sequence with a non-uniform probability.

__all__ defines the public objects within a module

How does splat unpacking work for sequences (*) and dictionaries (**).

Seeing something like @contract.bind indicates a decorator function in python.

A docstring is a the first unassigned string in a function, class, or module declaration.

The terminology makes finding a canonical “That’s a list / dict / etc. comprehension” question hard.

Why doesn’t my Python execute in this rendered JavaScript?

The representation of a string with backslashes can sometimes throw a user as they are escaped.

If a function does not return a value then it automatically returns None.

  • 1 - 100 of 107