Some Python Useful Ways
This Blog tracsfer from (here)[https://pythontips.com/2015/04/19/nifty-python-tricks/]
Enumerate
Instead of doing:
1 | i = 0 |
We can do:
1 | for i, item in enumerate(iterable): |
Enumerate can also take a second argument, Here is an example:
1 | >>> list(enumerate('abc')) |
Dict/Set comprehensions
You might know about list comprehensions but you might not be aware of dict/set comprehensions. They are simple to use and just as effective. Here is an example:
1 | my_dict = {i: i * i for i in xrange(100)} |
Forcing float divsion:
If we divide whole numbers Python gives us the result as a whole number even if the result was a float. In order to circumvent this issue we have to do something like this:
1 | result = 1.0 / 2 |
But there is another way to solve this problem which even I wasn’t aware of. You can do:
1 | from __futhure__ import division |
Now you don’t need to append .0 in order to get an accurate answer.
Do note that this trick is for Pyhton 2 only, In Python 3 there is no need to do the import as it handles this case by default.
Simple Server
Do you want to quickly and easily share files from a directory? You can simple do:
1 | # python 2 |
This would start up a server.
Evaluating Python expressions
We all know about eval but do we all know about literal_eval? Perhaps not. You can do:
1 | import ast |
Instead of:
1 | expr = "[1,2,3]" |
I am sure that it’s something new for most of us but it has been a part of Python for a long time.
Profiling a script
You can easily profile a script by runnung it like this:
1 | python -m cProfile my_script.py |
Object introspection
You can inspect objects in Python by using dir(). Here is a simple example:
1 | >>> foo = [1,2,3,4] |
Debugging script
You can easily set breakpoints in your script using the pdb module. Here is an example:
1 | import pdb |
You can write pdb.set_trace() anywhere in your script and it will set a breakpoint there. Super convenient. You should also read more about pdb as it has a couple of other hidden gems as welll.
Simplify if constructs
If you have to check for serveral values you can easily do:
1 | if n in [1,2,3,4]: |
instead of:
1 | if n == 1 or n == 2 or n == 3: |
Reversing a list/string
You can quickly reverse a list by using:
1 | >>> a = [1,2,3,4] |
and the same can be applied to a string as well:
1 | >>> foo = 'abcd' |
Pretty print
You can print dicts and lists in a beautiful way by doing:
1 | form pprint import pprint |
This is more effective on dicts. Moreover, if you want to pretty print json quickly from a file then you can simple do:
1 | cat file.json | python -m json.tools |
Ternary Operators
Ternary operators are shortcut for an if-else statement, and are also known as a conditional operators. Here are some example whick you can use to make your code compact and more beautiful.
1 | [on_true] if [expression] else [on_false] |