Saturday, May 4, 2024
HomePythonNifty Python methods - Yasoob Khalid

Nifty Python methods – Yasoob Khalid


Hello there people. It’s been a very long time since I final printed a publish. I’ve been busy. Nonetheless on this publish I’m going to share some actually informative ideas and methods which you may not have identified about. So with out losing any time lets get straight to them:

Enumerate

As an alternative of doing:

i = 0 
for merchandise in iterable: 
    print i, merchandise 
    i += 1

We will do:

for i, merchandise in enumerate(iterable):
    print i, merchandise

Enumerate also can take a second argument. Right here is an instance:

>>> record(enumerate('abc')) 
[(0, 'a'), (1, 'b'), (2, 'c')] 

>>> record(enumerate('abc', 1)) 
[(1, 'a'), (2, 'b'), (3, 'c')]

Dict/Set comprehensions

You may learn about record comprehensions however you may not concentrate on dict/set comprehensions. They’re easy to make use of and simply as efficient. Right here is an instance:

my_dict = {i: i * i for i in xrange(100)} 
my_set = {i * 15 for i in xrange(100)}

# There's solely a distinction of ':' in each

Forcing float division:

If we divide complete numbers Python provides us the end result as a complete quantity even when the end result was a float. As a way to circumvent this problem we have now to do one thing like this:

end result = 1.0/2

However there may be one other option to remedy this downside which even I wasn’t conscious of. You are able to do:

from __future__ import division 
end result = 1/2
# print(end result)
# 0.5

Voila! Now you don’t have to append .0 with a view to get an correct reply. Do be aware that this trick is for Python 2 solely. In Python 3 there isn’t any have to do the import because it handles this case by default.

Easy Server

Do you wish to shortly and simply share recordsdata from a listing? You’ll be able to merely do:

# Python2
python -m SimpleHTTPServer

# Python 3
python3 -m http.server

This may begin up a server.

Evaluating Python expressions

Everyone knows about eval however do everyone knows about _literaleval? Maybe not. You are able to do:

import ast 
my_list = ast.literal_eval(expr)

As an alternative of:

expr = "[1, 2, 3]" 
my_list = eval(expr)

I’m certain that it’s one thing new for many of us nevertheless it has been part of Python for a very long time.

Profiling a script

You’ll be able to simply profile a script by working it like this:

python -m cProfile my_script.py

Object introspection

You’ll be able to examine objects in Python through the use of dir(). Right here is an easy instance:

>>> foo = [1, 2, 3, 4]
>>> dir(foo) 
['__add__', '__class__', '__contains__', 
'__delattr__', '__delitem__', '__delslice__', ... , 
'extend', 'index', 'insert', 'pop', 'remove', 
'reverse', 'sort']

Debugging scripts

You’ll be able to simply set breakpoints in your script utilizing the _pdb _module. Right here is an instance:

import pdb
pdb.set_trace()

You’ll be able to write pdb.set_trace() anyplace in your script and it’ll set a breakpoint there. Tremendous handy. You must also learn extra about pdb because it has a few different hidden gems as effectively.

Simplify if constructs 

If you must test for a number of values you’ll be able to simply do:

if n in [1,4,5,6]:

as a substitute of:

if n==1 or n==4 or n==5 or n==6:

Reversing an inventory/string

You’ll be able to shortly reverse an inventory through the use of:

>>> a = [1,2,3,4]
>>> a[::-1]
[4, 3, 2, 1]

# This creates a brand new reversed record. 
# If you wish to reverse an inventory in place you are able to do:

a.reverse()

and the identical could be utilized to a string as effectively:

>>> foo = "yasoob"
>>> foo[::-1]
'boosay'

Fairly print

You’ll be able to print dicts and lists in an exquisite method by doing:

from pprint import pprint 
pprint(my_dict)

That is simpler on dicts. Furthermore, if you wish to fairly print json shortly from a file then you’ll be able to merely do:

cat file.json | python -m json.instruments

Ternary Operators

Ternary operators are shortcut for an if-else assertion, and are also referred to as a conditional operators. Listed below are some examples which you need to use to make your code compact and extra lovely.

[on_true] if [expression] else [on_false]
x, y = 50, 25
small = x if x < y else y

Thats all for immediately! I hope you loved this text and picked up a trick or two alongside the best way. See you within the subsequent article. Just remember to comply with us on Fb and Twitter!

Do you’ve gotten any feedback or recommendations? You’ll be able to write a remark or e mail me on yasoob.khld (at) gmail.com



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments