Top Python Tips & Tricks

Time Saving Tips And Tricks Of PythonTop Python Tips & TricksThese Must-Know Python Tips Make The Language BeautifulFarhad MalikBlockedUnblockFollowFollowingJun 14This article presents the Top Python tips and tricks to save you time and effort.

1.

Unpacking Array Itemsfirst_name, last_name = ['Farhad', 'Malik']print(first_name) #It will print Farhadprint(last_name) #It will print Malik2.

Swapping Variablesfirst_name, last_name = ['Farhad', 'Malik']last_name, first_name = first_name, last_nameprint(first_name) #It will print Malikprint(last_name) #It will print Farhad3.

Using Global Variablemy_global_variable = Truedef some_function(): global my_global_variable my_global_variable= Falsesome_function()print(my_global_variable) <–Returns False4.

Repeat String'A'*3 will repeat A three times: AAAPython Is A Great Language5.

Slicingy = 'Abc'y[:2] = aby[1:] = bcy[:-2] = ay[-2:] = bc6.

Reversingx = 'abc'x = x[::-1]7.

Negative IndexIf you want to start from the last character then use negative index.

y = 'abc'print(y[:-1]) # will return c8.

Intersect SetsTo get what’s common in two setsa = {1,2,3}b = {3,4,5}c = a.

intersection(b)9.

Difference In SetsTo retrieve the difference between two sets:a = {1,2,3}b = {3,4,5}c = a.

difference(b)10.

Union Of CollectionsTo get a distinct combined set of two setsa = {1,2,3}b = {3,4,5}c = a.

union(b)11.

Optional ArgumentsWe can pass in optional arguments by providing a default value to an argument:def my_new_function(my_value='hello'): print(my_value)#Callingmy_new_function() => prints hellomy_new_function('test') => prints test12.

Unknown Arguments Using *argumentsIf your function can take in any number of arguments then add a * in front of the parameter name:def myfunc(*arguments): return amyfunc(a)myfunc(a,b)myfunc(a,b,c)13.

Dictionary As Arguments Using **argumentsIt allows you to pass varying number of keyword arguments to a function.

You can also pass in dictionary values as keyword arguments:def myfunc(**arguments): return arguments['key']14.

Function With Multiple OutputsIf a function is required to return multiple values then:resultA, resultB = get_result()get_result() can return ('a', 1) which is a tuplePhoto by Max Nelson on Unsplash15.

One Liner For Loops[Variable] AggregateFunction([Value] for [item] in [collection])16.

Combining Lists Using ZipTakes multiple collections and returns a new collection.

The new collection contains items where each item contains one element from each input collection.

It allows us to transverse multiple collections at the same timename = 'farhad'suffix = [1,2,3,4,5,6]zip(name, suffix)–> returns (f,1),(a,2),(r,3),(h,4),(a,5),(d,6)17.

Free up MemoryManual garbage collection can be performed on timely or event based mechanism.

import gccollected_objects = gc.

collect()18.

Add Logging To Functions Using DecoratorsDecorators can add functionality to code.

They are essentially functions that call other objects/functions.

They are callable functions — therefore they return the object to be called later when the decorated function is invoked.

Think of decorates that enable aspect-oriented programmingWe can wrap a class/function and then a specific code will be executed any time the function is called.

def my_logger(function): @functools.

wraps(function) def logger(*args, **kwargs): print(function.

__name__) return function(*args, **kwargs) return loggerNow use it in your functions:@my_loggerdef hi(): print 'hi'@my_loggerdef bye(a): print 'bye' + a19.

Unzippingname = 'farhad'suffix = [1,2,3,4,5,6]result = zip(name, suffix)–> returns (f,1),(a,2),(r,3),(h,4),(a,5),(d,6)unzipped = zip(*result)20.

Joining Collectionname = ["FinTech", "Explained"] print(" ".

join(name))21.

Memory Footprint Of An Objectimport sys x = 'farhadmalik'print(sys.

getsizeof(x))22.

Print Current Directoryimport osprint(os.

getcwd())23.

Print Imported Modulesimport sysimported_modules = [m.

__name__ for m in sys.

modules.

values() if m]24.

Get Current Process Idimport osos.

getpid()I highly recommend this article if you want thorough understanding of Python:Everything About Python — Beginner To AdvancedEverything You Need To Know In One Articlemedium.

comHope the tips and tricks help.

.

. More details

Leave a Reply