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 - 13 of 13
  • 1

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

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

Unpacking assignment from a list, tuple, map, etc. into separate names

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.

TypeError: list indices must be integers or slices, not ...

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.

Python throws an error if you modify the dict you are currently iterating over. The obvious workaround is to copy the keys to a separate list, or collecting the keys to change into a separate list and modifying them separately after the loop.

How to remove items from a list while iterating over the same list without skipping elements.

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 splat operator (*) can be used to unpack variables from a container when calling a function.

  • 1 - 13 of 13
  • 1