You are on page 1of 11

List Comprehension

List Comprehension
• One of the most distinctive aspects of the language is the python list
and the list comprehension feature, which one can use within a single
line of code to construct powerful functionality.
• 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 expression, which is executed for
each element along with the for loop to iterate over each element.
Syntax:
newList = [ expression(element) for element in oldList if condition ]
• Advantages of List Comprehension
• More time-efficient and space-efficient than loops.
• Require fewer lines of code.
• Transforms iterative statement into a formula.
List Comprehensions vs For Loop
There are various ways to iterate through List Comprehensions translate the
a list. However, the most common traditional iteration approach using for
approach is to use the for loop. Let us loop into a simple formula hence making
look at the below example: them easy to use. Below is the approach
to iterate through a list, string, tuple, etc.
# Empty list
using list comprehension.
List = [] # Using list comprehension to iterate
through loop
# Traditional approach of iterating List = [character for character in 'Good
for character in 'Good Day!': Day!']
List.append(character)
# Displaying list
# Display list print(List)
[‘G’,‘o’,’o’,’d’, ‘’,’D’,’a’,’y’,’!’]
print(List)
The list comprehensions are more efficient both computationally
and in terms of coding space#and time than a for loop.
Driver Code
# Calculate time takens by for_loop()
# Import time module begin = time.time()
import time for_loop(10**6)
end = time.time()
# define function to implement for
# Display time taken by for_loop()
loop
print('Time taken for_loop:',round(end-begin,2))
def for_loop(n):
result = [] # Calculate time takens by list_comprehension()
for i in range(n): begin = time.time()
result.append(i**2) list_comprehension(10**6)
return result end = time.time()
# define function to implement list # Display time taken by for_loop()
comprehension print('Time taken for list_comprehension:',round(end-begin,2))
def list_comprehension(n): Time taken for_loop: 0.56
return [i**2 for i in range(n)] Time taken for list_comprehension: 0.47
Nested List Comprehensions

matrix = []
# Nested list comprehension
for i in range(3):
matrix = [[j for j in range(5)] for i in
range(3)]
# Append an empty sublist inside
the list
matrix.append([]) print(matrix)

for j in range(5):
matrix[i].append(j) [[0,1,2,3,4], [0,1,2,3,4], [0,1,2,3,4]]
print(matrix)
[[0,1,2,3,4], [0,1,2,3,4], [0,1,2,3,4]]
List Comprehensions and Lambda
• Lambda Expressions are nothing but #to print table of 10 using list
shorthand representations of Python comprehension
functions. numbers= [i*10 for i in range(1,6)]
• Using list comprehensions with lambda
creates an efficient combination. print(numbers)
# to print table of 10 using for loop
numbers = [] # using lambda to print table of 10
numbers = list(map(lambda i: i*10, [i for i
for i in range(1, 6): in range(1,6)]))
numbers.append(i*10)
print(numbers)
print(numbers)
[10, 20, 30, 40, 50]
Conditionals in List Comprehension
• Example 2: Display even elements from
• Example 1: Display square of a list of random numbers.
numbers from 1 to 10. # Assign matrix
# Getting square of even numbers twoDMatrix = [[10, 20, 30],
from 1 to 10 [40, 50, 60],
squares = [n**2 for n in range(1, [70, 80, 90]]
11) if n%2==0]
# Generate transpose
trans = [[i[j] for i in twoDMatrix] for j in
# Display square of even numbers range(len(twoDMatrix))]
print(squares)
print(trans)
[4, 16, 36, 64, 100]
[[10, 40, 70], [20, 50, 80], [30, 60, 90]]
Conditionals in List Comprehension
• Example 3: Toggle case of each character • Example 4: Reverse each string in
in a string. a tuple.
# Initializing string
# Reverse each string in tuple
string = 'Good Day'
List = [string[::-1] for string in (‘All',
# Toggle case of each character
‘is', ‘Well')]
List = list(map(lambda i: chr(ord(i)^32),
string)) # Display list
print(List)
# Display list
print(List)
['llA', 'si', 'lleW']
['g', 'O', 'O', 'D', '\x00', 'd', 'A', 'Y']
Key Points
• Comprehension of the list is an effective means of describing and
constructing lists based on current lists.
• Generally, list comprehension is more lightweight and simpler than
standard list formation functions and loops.
• We should not write long codes for list comprehensions in order to
ensure user-friendly code.
• Every comprehension of the list can be rewritten in for loop, but in
the context of list interpretation, every for loop can not be rewritten.
Difference between List comprehension and Lambda
• List comprehension is an elegant way to define
and create a list in python.
• We can create lists just like mathematical • In Python, anonymous function means
statements and in one line only. that a function is without a name.
• The syntax of list comprehension is easier to • As we already know the def keyword
grasp. A list comprehension generally consists of is used to define the normal functions
these parts : and the lambda keyword is used to
• Output expression, create anonymous functions.
• Input sequence,
• A variable representing a member of the input
sequence and lst = list(map(lambda x: x**2, range(1,
• An optional predicate part. 5)))
print(lst)
lst = [x ** 2 for x in range (1, 11) if x % 2 == 1] [1, 4, 9,16]
print(lst)
The difference between Lambdas and List
Comprehension
List Comprehension is used to create lists, Lambdas
are functions that can process like other functions # list comprehension
and thus return values or list.
list_comp = [x * 2 for x in list_]
# list from range 0 to 10 print(list_comp)
list_ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list_)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# lambda function
lambda_list = list(map(lambda x: x * 2, list_)) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Map basically iterates every element
# in the list_ and returns the lambda
# function result
print(lambda_list)

You might also like