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 129

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 new_list = old_list or new_dict = old_dict and is surprised when changes to the one reference are reflected in the other. The fix is to copy the list or dict in one of many ways.

An IndexError is raised because the asker tried using lst[len(lst)] = new_val to append to a list. They should have used lst.append (and maybe lst.extend) instead.

Make sure you are not name-clashing your modules

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

'12' < '2', and min(['12', '2']) == '12'

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 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?

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

Using open("relative/path") raises FileNotFoundError even though the file exists

Windows pathnames in source code with backslashes are fun.

listdir() returns just the file names; you have to os.path.join() back the directory name

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.

name = 'asdf'; foo.name isn’t the same as foo.asdf. You need getattr.

People get confused when 'longer string' < 'short string'.

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

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 pip nor pip3 corresponds to the version OP wants.

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 __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.

open('some file') for files located next to the module source, will fail when the current working directory does not match expectations. The solution is to use __file__ to construct an absolute path.

>>> '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?

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
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?

People get surprised when str.strip treats the argument as a set of characters to remove.

The caller gets a ValueError from using an array, frame, or series in a
boolean context.

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?

A typo like list["abcd"] instead of list("abcd") leads to Type Error: “'types.GenericAlias' object is not ...”

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

A type hint that tries to use a not-yet-defined name will throw a NameError.

User tries to read data from a file which is clearly not in UTF-8, but fails to understand that this is what the error message means.

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

  • 1 - 100 of 129