36
Beautiful Python: Some Cool Language Constructs and Tricks for Beginners
Python

1. Pretty printing of a dictionary

Suppose you have a nested dictionary and you want a human readable view of it, you could use json module to accomplish this. json.dumps() takes an extra parameter 'indent' that formats the elements legibly.

    >>> import json 
    >>> a = { 'a': {'b': {'c':'d', 'e':'f'}}}

    >>> print json.dumps(a, indent=2)
    {
      "a": {
        "b": {
          "c": "d",
          "e": "f"
        }
      }
    }

You can also use the pprint python module for pretty print of python data structures.

2. Reverse an iterable in python

>>> a = [1, 2, 4]

>>> a[::-1]
[4, 2, 1]

>>> a
[1, 2, 4]

>>> b = (2, 3, 4)

>>> b[::-1]
(4, 3, 2)

>>> b
(2, 3, 4)

>>> c = "This is a string"
>>> c[::-1]
'gnirts a si sihT'

>>> c
'This is a string'

This method always returns a new instance of the iterable instead of an in-place reverse.

3. Swapping the values of two variables in python

    >>> a = 1

    >>> b=2

    >>> a,b = b,a

    >>> a
    2

    >>> b
    1

How does this work?

Python separates the right-hand side expression from the left-hand side assignment. First the right-hand side is evaluated, and the result is stored on the stack, and then the left-hand side names are assigned using opcodes that take values from the stack again. For tuple assignments with 2 or 3 items, Python just uses the stack directly:

    >>> import dis
    >>> def foo(a, b):
         ...     a, b = b, a
         ... 
   >>> dis.dis(foo)
   2     0 LOAD_FAST                1 (b)
          3 LOAD_FAST                0 (a)
          6 ROT_TWO             
          7 STORE_FAST               0 (a)
         10 STORE_FAST              1 (b)
         13 LOAD_CONST            0 (None)
         16 RETURN_VALUE

After the two LOAD_FAST opcodes (which push a value from a variable onto the stack), the top of stack holds [a, b]. The ROT_TWO opcode swaps the top two positions on the stack so the stack now has [b, a] at the top. The two STORE_FAST opcodes then takes those two values and store them in the names on the left-hand side of the assignment. The first STORE_FAST pops a value of the top of the stack and puts it into a, the next pops again, storing the value in b. The rotation is needed because Python guarantees that assignments in a target list on the left-hand side are done from left to right.

For rest of the answer refer: http://stackoverflow.com/questions/21047524/how-does-swapping-of-members-in-the-python-tuples-a-b-b-a-work-internally

4. Enumerate

When you loop through a sequence or an iterable, you can get the index and its corresponding value at the same time by wrapping the sequence in enumerate.

    >>> for index, value in enumerate(['foo', 'bar', 'zoo']):
    ...     print index, value
    ...

    0 foo
    1 bar
    2 zoo

5. Splitting a string into a list of words and join them back

To split a string by whitespace

    >>> a = "This is a string"
    >>> a.split()
    ['This', 'is', 'a', 'string']

To split a string by a character

    >>> a = "This is a string"

    >>> a.split('s')

    ['Thi', ' i', ' a ', 'tring']

To join a list of words by space

    >>> b
    ['This', 'is', 'a', 'string']

    >>> " ".join(b)
    'This is a string'

To join a list of words by a character, comma for example

    >>> b
   ['This', 'is', 'a', 'string']

   >>> ",".join(b)
   'This,is,a,string'

6. List Comprehensions

Suppose you have a list of elements and you need to do some operation on each of the element. For example, you have a list L consisting of words each of length greater than 5 and you have to create a new list consisting of first three letters of each word in L. The common way to write code for this would be:

>>> L = ["Python", "makes", "people", "love her"]

>>> new_L = []

>>> for word in L:
...     new_L.append(word[0:3])
...

>>> new_L
['Pyt', 'mak', 'peo', 'lov']

This is where List comprehensions come to the rescue

>>> L = ["Python", "makes", "people", "love her"]

>>> new_L = [word[0:3] for word in L]

>>> new_L
['Pyt', 'mak', 'peo', 'lov']

This effectively reduced the number of lines from 3 in earlier approach to 1 using List comprehensions. Also, generally, List comprehensions are considered to be faster and efficient than creating an empty list and appending an element to that list one by one.

Now suppose you need only the words from L which have length>5.

>>> L = ["Python", "makes", "people", "love her"]

>>> new_L = [word for word in L if len(word)>5]

>>> new_L
['Python', 'people', 'love her']

Further reads on List Comprehensions:

[0] http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

[1] http://blog.cdleary.com/2010/04/efficiency-of-list-comprehensions/

[2] http://python-history.blogspot.in/2010/06/from-list-comprehensions-to-generator.html

Author

Notifications

?