Beautiful Python: Some Cool Language Constructs and Tricks for Beginners - Part 1


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

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

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

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

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


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






33 comments:

  1. Life is easy now! No need to plan for going out & get stuff you want to shop, Go to online shopping stores and select anything you like.online shopping pakistan Process is simple & quick. Your order will be reaching your home in two or three working days. You will be paying cash via bank transfer, easy paisa or cash on delivery when the product will reach at your place.
    Online Shopping in pakistan

    ReplyDelete
  2. Your order will be reaching your home in two or three working days. You will be paying cash via bank transfer, easy paisa or cash on delivery when the product will reach at your place. this is wrong, i can't understand this post.

    ReplyDelete
  3. Nice article thanks for sharing it...great job admin

    ReplyDelete
  4. Nice Information. Thanks for sharing to people such a great. getintopc

    ReplyDelete
  5. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    Java training in Chennai | Java training in Bangalore

    Java interview questions and answers | Core Java interview questions and answers

    ReplyDelete
  6. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    advanced excel training in bangalore | Devops Training in Chennai

    ReplyDelete
  7. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
    python training institute in marathahalli | python training institute in btm | Data Science training in Chennai

    ReplyDelete


  8. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.


    AWS Training in BTM Layout |Best AWS Training in BTM Layout

    AWS Training in Marathahalli | Best AWS Training in Marathahalli

    ReplyDelete
  9. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs Training in bangalore

    angularjs Training in bangalore

    ReplyDelete
  10. Online casino for everyone, come in and win now only we have the best online slots The best online slots we have.

    ReplyDelete
  11. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing.
    AWS Training in Chennai |Best Amazon Web Services Training in Chennai
    Best AWS Amazon Web Services Training in Chennai | AWS Training in Chennai cost
    No.1 AWS Training in Chennai | Amazon Web Services Training Institute in Chennai

    ReplyDelete
  12. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end. 
    microsoft azure training in bangalore
    rpa training in bangalore
    best rpa training in bangalore

    ReplyDelete
  13. I have picked cheery a lot of useful clothes outdated of this amazing blog. I’d love to return greater than and over again. Thanks! 
    python Course in Pune
    python Course institute in Chennai
    python Training institute in Bangalore

    ReplyDelete
  14. This comment has been removed by a blog administrator.

    ReplyDelete
  15. This comment has been removed by a blog administrator.

    ReplyDelete
  16. This comment has been removed by a blog administrator.

    ReplyDelete
  17. This comment has been removed by a blog administrator.

    ReplyDelete
  18. This comment has been removed by a blog administrator.

    ReplyDelete
  19. This comment has been removed by a blog administrator.

    ReplyDelete
  20. This comment has been removed by a blog administrator.

    ReplyDelete
  21. This comment has been removed by a blog administrator.

    ReplyDelete
  22. Great Article. Thank you for sharing! Really an awesome post for every one.

    IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    JavaScript Training in Chennai

    JavaScript Training in Chennai


    ReplyDelete