10 Top Python hacks, tips, and tricks for every coder
If you are into programming than Python is one coding language that is easiest for learners. Developed in the 80s, Python is open source and free to use, even for commercial applications. It is usually used and referred to as a scripting language, allowing programmers to roll out huge quantities of easily readable and functional code in short periods of time.
Further, Python is also dynamic and supports object-oriented, procedural, and functional programming styles, among others. Thanks to its flexibility, Python is one of the most widely used high-level programming languages today.
If you are learning Python, here are some awesome Python tricks you should know about.
Trick #1
List Comprehensions
Suppose you have a list:
>>>bag = [1, 2, 3, 4, 5]
Now you want to double each element in the list, so that it looks like this:
[2, 4, 6,8, 10]
Most beginners, coming from traditional languages will do something like this:
>>> bag = [1, 2, 3, 4, 5]
>>> for i in range(len(bag)):
>>> bag[i] = bag[i] * 2
But there’s a better way:
>>> bag = [elem * 2 for elem in bag]
This is called list comprehensions in Python.
For even more on list comprehensions, check out Trey Hunner’s tutorial.
Trick #2
Printing a List decently.
If you are a programmer you will know that Lists don’t print nicely. Though a programmer knows what the list is, but an average Joe doesn’t want to see brackets around everything. There’s a trivial solution to this, using a string’s ‘join’ method:
>>> recent_presidents = [‘George Bush’, ‘Bill Clinton’, ‘George W. Bush’]
>>> print ‘The three most recent presidents were: %s.’ % ‘, ‘.join(recent_presidents)
>>> prints ‘The three most recent presidents were: George Bush, Bill Clinton, George W. Bush.
The join method in Python turns the list into a string by casting each item into a string and connecting them with the string that join was called on. It’s even smart enough to not put one after the last element. As an added advantage, this is pretty fast, running in linear time. Don’t ever create a string by ‘+’ing list items together in a for loop: not only is it ugly, but it takes much longer.
Trick #3
a = [“Code”, “mentor”, “Python”, “Developer”]
Create a single string from all the elements in list above.
>>> print ” “.join(a)
The result will be
Code mentor Python Developer
Trick #4
Write a Python code to print
list1 = [‘a’, ‘b’, ‘c’, ‘d’]
list2 = [‘p’, ‘q’, ‘r’, ‘s’]
ap
bq
cr
ds
>>> for x, y in zip(list1,list2):
… print x, y
…
a p
b q
c r
d s
Trick #5
Swap two numbers with one line of code :
>>> a=7
>>> b=5
>>> b, a =a, b
>>> a
5
>>> b
7
Trick #6
print “codecodecodecode mentormentormentormentorm
>>> print “code”*4+‘ ‘+“mentor”*5
The result will be as follows :
codecodecodecode mentormentormentormentorm
entor
Trick #7
Convert it to a single list without using any loops.
a = [[1, 2], [3, 4], [5, 6]]
Output:- [1, 2, 3, 4, 5, 6]
>>> import itertools
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]
Trick #8
Checking if two words are anagrams
def is_anagram(word1, word2):
“””Checks whether the words are anagrams.
word1: string
word2: string
returns: boolean
“””
Complete the above method to find if two words are anagrams.
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
>>> is_anagram(‘abcd’,’dbca’)
True
>>> is_anagram(‘abcd’,’dbaa’)
False
Trick #9.
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.
>>> result = map(lambda x:int(x) ,raw_input().split())
1 2 3 4
>>> result
[1, 2, 3, 4]
Trick #10
Reversing a string in Python
>>> a = “ilovepython”
>>> print “Reverse is”,a[::-1]
Reverse result is
nohtypevoli
This is a quaint Python trick you should know
SimpleHTTPServer
The SimpleHTTPServer module that comes with Python is a simple HTTP server that provides standard GET and HEAD request handlers.
Why should I use it?
An advantage with the built-in HTTP server is that you don’t have to install and configure anything. The only thing that you need, is to have Python installed. That makes it perfect to use when you need a quick web server running and you don’t want to mess with setting up apache. You can use this to turn any directory in your system into your web server directory.
How do I use it?
To start a HTTP server on port 8000 (which is the default port), simple type:
python –m SimpleHTTPServer [port]
This will now show the files and directories which are in the current working directory. You can also change the port to something else:
$ python –m SimpleHTTPServer 8080
How to share files and directories
In your terminal, cd into whichever directory you wish to have accessible via browsers and HTTP.
cd /var/www/
$ python –m SimpleHTTPServer
After you hit enter, you should see the following message:
Serving HTTP on 0.0.0.0 port 8000 …
Open your favorite browser and put in any of the following addresses:
https://your_ip_address:8000
https://127.0.0.1:8000
If you don’t have an index.html file in the directory, then all files and directories will be listed. As long as the HTTP server is running, the terminal will update as data are loaded from the Python web server. You should see standard http logging information (GET and PUSH), 404 errors, IP addresses, dates, times, and all that you would expect from a standard http log as if you were tailing an apache access log file.