Idioms

A programming idiom, put simply, is a way to write code. The notion ofprogramming idioms is discussed amply at c2and at Stack Overflow.

Idiomatic Python code is often referred to as being Pythonic.

Although there usually is one — and preferably only one — obvious way to doit; the way to write idiomatic Python code can be non-obvious to Pythonbeginners. So, good idioms must be consciously acquired.

Some common Python idioms follow:

Unpacking

If you know the length of a list or tuple, you can assign names to itselements with unpacking. For example, since enumerate() will providea tuple of two elements for each item in list:

  1. for index, item in enumerate(some_list):
  2. # do something with index and item

You can use this to swap variables as well:

  1. a, b = b, a

Nested unpacking works too:

  1. a, (b, c) = 1, (2, 3)

In Python 3, a new method of extended unpacking was introduced byPEP 3132:

  1. a, *rest = [1, 2, 3]
  2. # a = 1, rest = [2, 3]
  3. a, *middle, c = [1, 2, 3, 4]
  4. # a = 1, middle = [2, 3], c = 4

Create an ignored variable

If you need to assign something (for instance, in Unpacking) butwill not need that variable, use __:

  1. filename = 'foobar.txt'
  2. basename, __, ext = filename.rpartition('.')

Note

Many Python style guides recommend the use of a single underscore “”for throwaway variables rather than the double underscore “__”recommended here. The issue is that “” is commonly used as an aliasfor the gettext() function, and is also used at theinteractive prompt to hold the value of the last operation. Using adouble underscore instead is just as clear and almost as convenient,and eliminates the risk of accidentally interfering with either ofthese other use cases.

Create a length-N list of the same thing

Use the Python list * operator:

  1. four_nones = [None] * 4

Create a length-N list of lists

Because lists are mutable, the * operator (as above) will create a listof N references to the same list, which is not likely what you want.Instead, use a list comprehension:

  1. four_lists = [[] for __ in xrange(4)]

Note: Use range() instead of xrange() in Python 3.

Create a string from a list

A common idiom for creating strings is to use str.join() on an emptystring.

  1. letters = ['s', 'p', 'a', 'm']
  2. word = ''.join(letters)

This will set the value of the variable word to ‘spam’. This idiom can beapplied to lists and tuples.

Searching for an item in a collection

Sometimes we need to search through a collection of things. Let’s look at twooptions: lists and sets.

Take the following code for example:

  1. s = set(['s', 'p', 'a', 'm'])
  2. l = ['s', 'p', 'a', 'm']
  3.  
  4. def lookup_set(s):
  5. return 's' in s
  6.  
  7. def lookup_list(l):
  8. return 's' in l

Even though both functions look identical, because lookup_set is utilizingthe fact that sets in Python are hashtables, the lookup performancebetween the two is very different. To determine whether an item is in a list,Python will have to go through each item until it finds a matching item.This is time consuming, especially for long lists. In a set, on the otherhand, the hash of the item will tell Python where in the set to look fora matching item. As a result, the search can be done quickly, even if theset is large. Searching in dictionaries works the same way. Formore information see thisStackOverflowpage. For detailed information on the amount of time various common operationstake on each of these data structures, seethis page.

Because of these differences in performance, it is often a good idea to usesets or dictionaries instead of lists in cases where:

  • The collection will contain a large number of items
  • You will be repeatedly searching for items in the collection
  • You do not have duplicate items. For small collections, or collections which you will not frequently besearching through, the additional time and memory required to set up thehashtable will often be greater than the time saved by the improved searchspeed.