15 Essential Python Tips And Tricks For Programmers
Tips#1. In-Place Swapping Of Two Numbers.
Python provides an intuitive way to do assignments and swapping in one line. Please refer to the below example.
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#1 (10, 20)
#2 (20, 10)
The assignment on the right seeds a new tuple. While the left one instantly unpacks that (unreferenced) tuple to the names <a> and <b>.
Once the assignment is through, the new tuple gets unreferenced and flagged for garbage collection. The swapping of variables also occurs at eventually.
TOC
Tips#2. Chaining Of Comparison Operators.
Aggregation of comparison operators is another trick that can come handy at times.
n = 10
result = 1 < n < 20
print(result)
# True
result = 1 > n <= 9
print(result)
# False
TOC
Tips#3. Use Of Ternary Operator For Conditional Assignment.
Ternary operators are a shortcut for an if-else statement and also known as conditional operators.
[on_true] if [expression] else [on_false]
Here are a few examples which you can use to make your code compact and concise.
The below statement is doing the same what it is meant to i.e. “assign 10 to x if y is 9, otherwise assign 20 to x“. We can though extend the chaining of operators if required.
x = 10 if (y == 9) else 20
Likewise, we can do the same for class objects.
x = (classA if y == 1 else classB)(param1, param2)
In the above example, classA and classB are two classes and one of the class constructors would get called.
Below is one more example with a no. of conditions joining to evaluate the smallest number.
def small(a, b, c):
return a if a <= b and a <= c else (b if b <= a and b <= c else c)
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))
#Output
#0 #1 #2 #3
We can even use a ternary operator with the list comprehension.
[m**2 if m > 10 else m**4 for m in range(50)]
#=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
TOC
Tips#4. Work With Multi-Line Strings.
The basic approach is to use backslashes which derive itself from C language.
multiStr = "select * from multi_row \
where row_id < 5"
print(multiStr)
# select * from multi_row where row_id < 5
One more trick is to use the triple-quotes.
multiStr = """select * from multi_row
where row_id < 5"""
print(multiStr)
#select * from multi_row
#where row_id < 5
The common issue with the above methods is the lack of proper indentation. If we try to indent, it’ll insert whitespaces in the string.
So the final solution is to split the string into multi lines and enclose the entire string in parenthesis.
multiStr= ("select * from multi_row "
"where row_id < 5 "
"order by age")
print(multiStr)
#select * from multi_row where row_id < 5 order by age
TOC
Tips#5. Storing Elements Of A List Into New Variables.
We can use a list to initialize a no. of variables. While unpacking the list, the count of variables shouldn’t exceed the no. of elements in the list.
testList = [1,2,3]
x, y, z = testList
print(x, y, z)
#-> 1 2 3
TOC
Tips#6. Print The File Path Of Imported Modules.
If you want to know the absolute location of modules imported in your code, then use the below trick.
import threading
import socket
print(threading)
print(socket)
#1- <module 'threading' from '/usr/lib/python2.7/threading.py'>
#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>
TOC
Tips#7. Use The Interactive “_” Operator.
It’s a useful feature which not many of us know.
In the Python console, whenever we test an expression or call a function, the result dispatches to a temporary name, _ (an underscore).
>>> 2 + 1
3
>>> _
3
>>> print _
3
The “_” references to the output of the last executed expression.
TOC
Tips#8. Dictionary/Set Comprehensions.
Like we use list comprehensions, we can also use dictionary/set comprehensions. They are simple to use and just as effective. Here is an example.
testDict = {i: i * i for i in xrange(10)}
testSet = {i * 2 for i in xrange(10)}
print(testSet)
print(testDict)
#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Note- There is only a difference of <:> in the two statements. Also, to run the above code in Python3, replace <xrange> with <range>.
TOC
Tips#9. Debugging Scripts.
We can set breakpoints in our Python script with the help of the <pdb> module. Please follow the below example.
import pdb
pdb.set_trace()
We can specify <pdb.set_trace()> anywhere in the script and set a breakpoint there. It’s extremely convenient.
TOC
Tips#10. Setup File Sharing.
Python allows running an HTTP server which you can use to share files from the server root directory. Below are the commands to start the server.
# Python 2
python -m SimpleHTTPServer
# Python 3
python3 -m http.server
Above commands would start a server on the default port i.e. 8000. You can also use a custom port by passing it as the last argument to the above commands.
TOC
Tips#11. Inspect An Object In Python.
We can inspect objects in Python by calling the dir() method. Here is a simple example.
test = [1, 3, 5, 7]
print( dir(test) )
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
TOC
Tips#12. Simplify If Statement.
To verify multiple values, we can do in the following manner.
if m in [1,3,5,7]:
instead of:
if m==1 or m==3 or m==5 or m==7:
Alternatively, we can use ‘{1,3,5,7}’ instead of ‘[1,3,5,7]’ for ‘in’ operator because ‘set’ can access each element by O(1).
TOC
Tips#13. Detect Python Version At Runtime.
Sometimes we may not want to execute our program if the Python engine currently running is less than the supported version. To achieve this, you can use the below coding snippet. It also prints the currently used Python version in a readable format.
import sys
#Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
print("Sorry, you aren't running on Python 3.5\n")
print("Please upgrade to 3.5.\n")
sys.exit(1)
#Print Python version in a readable format.
print("Current Python version: ", sys.version)
Alternatively, you can usesys.version_info >= (3, 5) to replacesys.hexversion!= 50660080 in the above code. It was a suggestion from one of the informed reader.
Output when running on Python 2.7.
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
Sorry, you aren't running on Python 3.5
Please upgrade to 3.5.
Output when running on Python 3.5.
Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05)
[GCC 5.3.0]
TOC
Tips#14. Combining Multiple Strings.
If you want to concatenate all the tokens available in a list, then see the below example.
>>> test = ['I', 'Like', 'Python', 'automation']
Now, let’s create a single string from the elements in the list given above.
>>> print ''.join(test)
TOC
Tips#15. Four Ways To Reverse String/List.
# Reverse The List Itself.
testList = [1, 3, 5]
testList.reverse()
print(testList)
#-> [5, 3, 1]
# Reverse While Iterating In A Loop.
for element in reversed([1,3,5]): print(element)
#1-> 5
#2-> 3
#3-> 1
# Reverse A String In Line.
"Test Python"[::-1]
This gives the output as ”nohtyP tseT”
# Reverse A List Using Slicing.
[1, 3, 5][::-1]
The above command will give the output as [5, 3, 1].
TOC
Hope you liked it.