Cool Python tricks and tips

Tags: ,

Here are some cool tricks to write better python code:

List comprehensions:

Instead of building a list with a loop:


We can often build it much more concisely with a list comprehension:

 

Enumerate

We can use enumerate to do a for loop:

like this:

Enumerate can also take a second argument. Here is an example:

 

Dict/Set comprehensions

dict/set comprehensions are simple to use and just as effective:

 

Simple Server

In can we can simply start a web server like this:

After you hit enter, you should see the following message:

Serving HTTP on 0.0.0.0 port 8080 …

Open your favorite browser and put in any of the following addresses:

http://your_ip_address:8080

http://127.0.0.1:8080

Evaluating Python expressions

The following two do the same thing:

 

Object introspection

We can inspect objects in Python by using dir():

 

Simplify if constructs 

If we have to check for several values we can do:

instead of:

 

Reversing a list/string

To reverse a list:

and the same can be applied to a string as well:

Pretty print

You can print dicts and lists in a beautiful way by doing:

This is more effective on dicts. Moreover, if you want to pretty print json quickly from a file then you can simply do:

 

Ternary Operators

Ternary operators are shortcut for an if-else statement, and are also known as a conditional operators. 

 

Fun tricks with zip

Transposing a matrix:

  1. >>> l = [[1, 2, 3], [4, 5, 6]]
  2. >>> zip(*l)
  3. [(1, 4), (2, 5), (3, 6)]


Dividing a list into groups of n:

  1. >>> l = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8]
  2. >>> zip(*[iter(l)] * 3)
  3. [(3, 1, 4), (1, 5, 9), (2, 6, 5), (3, 5, 8)]

Another example to use zip

Write a Python code to print

ap

bq

cr

ds

  1. a p
  2. b q
  3. c r
  4. d s

 

Create a String from a list:

Create a single string from all the elements in list above.

 

Swap two numbers with one line of code.

  1. >>> a=7

  2. >>> b=5

  3. >>> b, a =a, b

  4. >>> a

  5. 5

  6. >>> b

  7. 7

 

repeat strings

print “codecodecodecode mentormentormentormentormentor” without using loops

  1. >>> print “code”*4+‘ ‘+“mentor”*5

codecodecodecode mentormentormentormentormentor

Flatten a nested list

Convert it to a single list without using any loops.

  1. a = [[1, 2], [3, 4], [5, 6]]

Output:- [1, 2, 3, 4, 5, 6]

  1. >>> import itertools
  2. >>> list(itertools.chain.from_iterable(a))
  3. [1, 2, 3, 4, 5, 6]

Use Map

Take a string input.

For example “1 2 3 4” and return [1, 2, 3, 4]

Remember list being returned has integers in it. Don’t use more than one line of code.

  1. >>> result = map(lambda x:int(x) ,raw_input().split())
  2. 1 2 3 4
  3. >>> result
  4. [1, 2, 3, 4]

startswith parameters

Instead of:

if s.startswith('http://') or s.startswith('https://'):

You can use:

if s.startswith(('http://', 'https://')):

NOTE: And the same with endswith and isinstance(1, (int, float))

 

Be careful with mutable default arguments

Instead, you should use a sentinel value denoting “not given” and replace with the mutable you’d like as default:

 

The Awesome Module Itertools

Along with the collections library python also has a library called itertools which has really cool efficient solutions to problems. One is finding all combinations. This will tell us all the different ways the teams can play each other.

 

Named tuples:

Now you can index by keyword, much nicer than offset into tuple by number (less readable)

Elegantly used when looping through a csv:

We can use the unpacking star feature to throw away useless fields:

 

Use the defaultdict:

So we don’t need to init the list each time which leads to needless code:

You can use OrderedDict to leave the order of inserted keys:

 

Counter:

 

Sorted by specified column

sorted() accepts a key arg which you can use to sort on something else

For example:

 

Create XMl from dict

Creating XML tags manually is usually a bad idea, I bookmarked this simple dict_to_xml helper:

 

One line code to check if a file exists in a directory

 

Use set to get the common items in lists

Use set operations to match common items in lists

 

I hope these tricks are useful to you. Please leave a comment to share other python tricks. 

https://gist.github.com/douglasmiranda/3262157

Nifty Python tricks

https://www.quora.com/What-are-some-cool-Python-tricks

http://bobbelderbos.com/2016/06/python-tips/