Python: List Comprehension and Lambda Operations

Python: List Comprehension and Lambda Operations

Explanation and code for List Comprehension and Lambda Operations in Python

List Comprehension

List Comprehension is an easy way to create lists. To create a list we follow a syntax like this:

new_list = []
for i in old_list:
    if somecriteria(i):
        new_list.append(operation_with(i))

To make it more concrete let’s give an example:

old_list = [1,2,3,4,5]
new_list = []

for i in old_list:
    if(i%2 == 0):
        new_list.append(i**2)

To write the first expression with list comprehension we do this:

new_list = [operation_with(i) for i in old_list if somecriteria(i)]

So our concrete example turns into this:

new_list = [i**2 for i in old_list if i%2 == 0]

Lambda Operations

Lambda expressions allow us to define a function anonymously. So instead of formally doing this:

def hello_world():
    print("Hello World")

We can write this with a lambda expression like this:

hello_world = lambda :print("Hello World")

We can also write functions which take arguments with lambda expressions as well:

# Formal way
def add_two(a,b):
    return a+b

# Lambda
add_two = lambda a,b: return a+b

The main difference is the variable name which makes it usable by add_two() syntax is optional here. But plainly what does it do? These examples don’t give justice on lambda expressions. Basically this can be thought as the LINQ operator used in C#. I think another example, which actually shows what a lambda does can follow:

names = ["Ozgur","Ahmet","Mehmet"]

# Old Way
def lowercase(name):
    return name.lower()

lowercased_names = map(lowercase,names)

# Lambda way
lowercased_names = map(lambda name:name.lower(), names)