30 Days Of Python πŸ‘¨β€πŸ’» - Day 12 - Lambda Expression And Comprehensions

This article is a part of a 30 day Python challenge series. You can find the links to all the previous posts of this series here
Functional Programming in itself is a big topic and there are a lot of concepts in it to understand and master. However, I have a defined goal to learn Python in 30 days, so I rather prefer to understand the key concepts and learn the most commonly used techniques that would come in handy in building practical projects.
 
I explored the fundamentals of functional programming and how it is implemented in Python yesterday. Today, I explored the missing pieces and I came across quite interesting findings while doing so which I will be sharing in this post.
 

Lamba Expressions

 
Lambda is actually a term in computer science which means an anonymous function which is used only once while the expression is being executed. Lambda expressions are quite useful to simplify code and make functions more concise and compact. However, overusing them in complicated evaluations can make the code less readable. Every cool thing has their trade-off as well!
 
Upon exploring their syntax and use cases, it immediately made me think of arrow functions syntax from the JavaScript universe although they are not exactly similar.
  1. names = ['John''Peter''Elon''Joseph']  
  2.   
  3. # make all names upper cased  
  4. uppercased = list(map(lambda name: str.upper(name), names))  
  5.   
  6. print(uppercased)  
Lambda takes any number of arguments (here name) and expression involving the arguments (here str.upper(name)).
  1. users = [('Mary'23), ('Emilie'10), ('Katie'30)]  
  2.   
  3. sorted_by_name = sorted(users)  
  4. print(sorted_by_name)   
  5. # [('Emilie', 10), ('Katie', 30), ('Mary', 23)]  
  6.   
  7. sorted_by_age = sorted(users, key = lambda item: item[1])   
  8. # using age as key for sorting   
  9.   
  10. print(sorted_by_age)  
  11. # [('Emilie', 10), ('Mary', 23), ('Katie', 30)]  
  1. scores = [235520903453]  
  2.   
  3. scores_under50 = list(filter(lambda x: x < 50, scores))  
  4. print(scores_under50) # [23, 20, 34]  

Comprehensions

 
Comprehensions are another cool feature of Python which I found really useful. They are used to quickly build data structures such as list, set, dict in a compact syntax and are said to be faster as compared to creating the same data structures using loops.
 
It can often be tempting to replace loops with comprehensions. However, a cleverly written code is not always good in terms of readability. So lengthy one-liner comprehensions should be avoided as it may look very compact but might hurt someone’s brain πŸ˜ƒ
 
Comprehensions are of the following kind in Python - List comprehension, Set Comprehension and Dict Comprehension.
 
List Comprehension
 
Suppose we have to create a list of characters from a string, the simple way would be something like this
  1. name = 'python'  
  2.   
  3. new_list = []  
  4. for character in name:  
  5.   new_list.append(character)  
  6.   
  7. print(new_list)   
  8. # ['p', 'y', 't', 'h', 'o', 'n']  
However, using list comprehension it can be more concise
  1. name = 'python'  
  2. new_list = [item for item in name] # here item can be any name  
  3.   
  4. print(new_list)  
  1. # Quickly generates a list of 10 items with their values squared  
  2. new_list = [item**2 for item in range(10)]  
  3. print(new_list) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]  
It is also possible to add a condition to the comprehension
  1. numbers = [2,34,23,53,34,12,22,89]  
  2.   
  3. even_numbers = [num for num in numbers if num % 2 == 0]  
  4. print(even_numbers) # [2, 34, 34, 12, 22]  
  1. brands = [  
  2.   {'name''Nike''category''shoes'},  
  3.   {'name''Reebok''category''shoes'},  
  4.   {'name''Tesla''category''cars'},  
  5.   {'name''Adidas''category''shoes'},  
  6.   ]  
  7.   
  8. car_brands = [item for item in brands if item['category'] =='shoes']  
  9. print(car_brands) # filters out Tesla  
Set Comprehension
  1. names = ['Rick''Alan''Rick''Mike']  
  2. new_set = {item for item in names}  
  3.   
  4. print(new_set) # {'Mike', 'Alan', 'Rick'}  
Dictionary Comprehension
  1. attendance = {  
  2.     'John'True,  
  3.     'David'False,  
  4.     'Nick'True,  
  5.     'Tom'False,  
  6.     'Marie'False,  
  7.     'Nancy'True  
  8. }  
  9.   
  10. students_present = {key:value for key,value in attendance.items() if value}  
  11. print(students_present)  
  12. # {'John': True, 'Nick': True, 'Nancy': True}  

Quick Coding Exercise

 
From a list of names, filter out the duplicate names and store in a list.
 
I solved this before while exploring loops and functions. Today I will try to recreate the solution using comprehensions.
  1. names = [  
  2.     'Harry''Johnny''Lewis''Harry''Buck''Nick''David''Harry',  
  3.     'Lewis''Michael'  
  4. ]  
  5.   
  6. duplicate_names = list(set([name for name in names if names.count(name) > 1]))  
  7.   
  8. print(duplicate_names) # ['Lewis', 'Harry']  
The solution is a one-liner and looks very clever but one can argue against it being less readable.
 
Anyways it's good to know alternatives. I prefer to be more verbose while writing in practical projects so it’s less clever code and more readable code.
 
That’s all for today’s exploration of functional programming. I think I have pretty much covered most of the essentials.
 
Tomorrow, I plan to dig into decorators in Python. I am sure that will be exciting and fun.
 
Have a great one!