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:

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

    You can use this to swap variables as well:

    1. a, b = b, a

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

      Create an ignored variable

      If you need to assign something (for instance, in ) 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.

      Use the Python list operator:

      1. four_nones = [None] * 4

      Create a length-N list of lists

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

      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. def lookup_set(s):
      4. return 's' in s
      5.  
      6. def lookup_list(l):
      7. return 's' in l

      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