Open In App

Difference between List comprehension and Lambda in Python

Last Updated : 15 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. 

A list comprehension generally consists of these parts :

  • Output expression,
  • Input sequence,
  • A variable representing a member of the input sequence and
  • An optional predicate part.

Syntax of list comprehension

List = [expression(i) for i in another_list if filter(i)]

Example: 

Python3




lst = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(lst)


Output:

[1, 9, 25, 49, 81]

In the above example,

  • x ** 2 is the expression.
  • range (1, 11) is an input sequence or another list.
  • x is the variable.
  • if x % 2 == 1 is predicate part.

What is lambda?

In Python, an anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. It has the following syntax: 

Syntax of lambda

lambda arguments : expression

Example: 

Python3




lst = list(map(lambda x: x**2, range(1, 5)))
print(lst)


Output:

[1, 4, 9, 16]

The difference between Lambda and List Comprehension

List Comprehension is used to create lists, Lambda is function that can process like other functions and thus return values or lists. 

Example: 

Python3




# list from range 0 to 10
list_ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list_)
  
# lambda function
lambda_list = list(map(lambda x: x * 2, list_))
 
# Map basically iterates every element
# in the list_ and returns the lambda
# function result
print(lambda_list)
  
# list comprehension
list_comp = [x * 2 for x in list_]
print(list_comp)


Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Graphical representation of list comprehension vs lambda + filter

As we can see from the graph that overall list comprehension is much faster than the filter function. The filter is faster for a small list only.

Python3




import numpy as np
import matplotlib.pyplot as plt
import time
 
 
# Compare runtime of both methods
sizes = [i * 10000 for i in range(100)]
 
filter_runtimes = []
list_comp_runtimes = []
 
for lis_size in sizes:
 
    lst = list(range(lis_size))
 
    # Get time stamps
    time_A = time.time()
    list(filter(lambda x: x % 2, lst))
    time_B = time.time()
    [x for x in lst if x % 2]
    time_C = time.time()
 
    # Calculate runtimes
    filter_runtimes.append((lis_size, time_B - time_A))
    list_comp_runtimes.append((lis_size, time_C - time_B))
 
 
# list comprehension vs. lambda + filter using Matplotlib
 
filt = np.array(filter_runtimes)
lis = np.array(list_comp_runtimes)
 
plt.plot(filt[:, 0], filt[:, 1], label='filter')
plt.plot(lis[:, 0], lis[:, 1], label='list comprehension')
 
plt.xlabel('list size')
plt.ylabel('runtime in seconds)')
 
plt.legend()
plt.show()


Output:

 



Previous Article
Next Article

Similar Reads

Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python Program to Square Each Odd Number in a List using List Comprehension
Given a list, the task is to write a Python Program to square each odd number in a list using list comprehension. Square Each Odd Number in a List using List Comprehension List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expres
3 min read
Appending Item to Lists of list using List Comprehension | Python
If you are a Python user, you would know that in Python, we can use the append() method to add an item to an existing list. This list may already contain other items or be empty. Further, the item to be added can simply be a number a character, or even an entire tuple or list. However, if you are trying to append an item to lists within a list comp
5 min read
Difference between Normal def defined function and Lambda
In this article, we will discuss the difference between normal def defined function and lambda in Python. Def keyword​​​​​​​In python, def defined functions are commonly used because of their simplicity. The def defined functions do not return anything if not explicitly returned whereas the lambda function does return an object. The def functions m
2 min read
Difference Between Lambda and Amplify in AWS
Pre-requisite: AWS By using the computing service offered by Amazon Lambda, you may run code without installing or managing servers. Almost any type of backend service or application may be executed with Lambda. Providing Lambda with your code in one of the languages it supports is all that is necessary. Lambda manages all compute resource manageme
3 min read
Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
We are given an array of n distinct numbers, the task is to sort all even-placed numbers in increasing and odd-place numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers. Note that the first element is considered as even because of its index 0. Examples: Input: a
2 min read
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
5 min read
K’th Non-repeating Character in Python using List Comprehension and OrderedDict
Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: Input : str = geeksforgeeks, k = 3 Output : r First non-repeating character is f, second is o and t
2 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Program to Sort the list according to the column using lambda
Given a list, the task is to sort the list according to the column using the lambda approach. Examples: Input : array = [[1, 3, 3], [2, 1, 2], [3, 2, 1]] Output : Sorted array specific to column 0, [[1, 3, 3], [2, 1, 2], [3, 2, 1]] Sorted array specific to column 1, [[2, 1, 2], [3, 2, 1], [1, 3, 3]] Sorted array specific to column 2, [[3, 2, 1], [2
2 min read
Practice Tags :