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

= [“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 mentormentormentormentormentor” without using loops
>>> PRINT “CODE”*4+‘ ‘+“MENTOR”*5
The result will be as follows :
CODECODECODECODE MENTORMENTORMENTORMENTORMENTOR

Trick #7

Convert it to a single list without using any loops.
= [[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 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 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 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:

HTTP://YOUR_IP_ADDRESS:8000
HTTP://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.

Comments