3 Tricks to write code in a Pythonic way

Sayantanee Sen
Analytics Vidhya
Published in
3 min readJul 13, 2021
Photo by David Heslop on Unsplash

With the growing edge technology demand in fields like Data Analytics, Data Visualization, Machine Learning, Web Development and Game Development, Python has become one of the most profound coding language in the recent times.

While the news of powerful python packages getting launched everyday continue to excite us, we often miss to leverage the basic functionalities that Python has to offer. In this article, I will be discussing three such python topics that can help you write code better and more efficiently.

List Comprehension

We can always create a list in the convention way using loops. However, the more Pythonic and not to mention easier way to do this is using comprehensions. Here are few handy functionalities of list comprehensions.

  • One-Line : Create a list of integer numbers from 1 to 100, no problem!
numbers=[i for i in range(1,101)]
  • Conditional : Create a list with only even numbers, ranges from 1 to 100
  • Iterable: Create a list of numbers with items from a second list

Dictionary and Set Comprehensions (Bonus): These data structures cater same functionality as list comprehensions.

  • Set comprehensions:
oops! That’s my name without dupes
  • Dictionary comprehensions:

The Power of Lambda

Lambda functions are anonymous or throwaway functions as they are mainly used for one time use functionalities . However, the real potential of Lambda can be seen when you combine it with other functions.

  • Lambda with filter() : Filter function takes a function and a list as arguments.
Prints all evens
  • Lambda with map() : Map function also takes a function and list as arguments.
Multiplies all elements with 2
  • Lambda with reduce() : Reduce function decreases the size of the list into one return value.
Returns sum of all numbers

Zip() it!

Let me explain this cool function with an example. Let us create two dataframes as below.

df = pd.DataFrame({ 'Id': [1,2,3,4,5,6,7,8,9,10],'Employee': ["A","B","C","D","E","F","G","H","I","J"],
'Location': ["Ind","Ind","US","Eur","Eur","Eur","Ind","US","Ind","US"]})
look_up_df=pd.DataFrame({'location_code':["Ind","US","Eur"], 'description':["India","United States","Europe"]})
Our Dataset
Location Look ups

Now say you want to replace each of the location code with the respective description, we can simply use zip, here is how:

df.replace(dict(zip(look_up_df['location_code'],look_up_df['description'])),inplace=True)

Let us break this down. zip() function will take in two iterable objects and return an iterator of tuples, which we then convert into a dictionary and use as a parameter to our replace function.

Zip() returns this in our example
  • Unzipping will get our original series back.
z=zip(look_up_df['location_code'],look_up_df['description'])
codes, desc = zip(*z)
print('location_code =', codes)
print('description =', desc)

Happy Coding!

--

--