3 Tricks to write code in a Pythonic way
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!
- 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:
- 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.
- Lambda with map() : Map function also takes a function and list as arguments.
- Lambda with reduce() : Reduce function decreases the size of the list into one return value.
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"]})
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.
- 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!