List comprehension is a technique of creating new lists using other iterable and in fewer lines of codes. The iterable object which can be used in this technique can be any data structure like list, tuple, set, string and dictionary, etc. An iterable created by using range() function can also be used here.
The syntax used in list comprehension generally contains three segments:
- iterable: iterable object like list, tuple, set, string, dictionary, etc.
- transformation function: a transformation function that needs to be applied to the iterable.
- filters: filters/conditions which are required to apply on iterable.
Syntax
#list comprehension syntax list = [tranform_func(i) for i in iterable if filters] #which is equivalent to... for i in iterator: if filters: list.append(tranform_func(i))
Example: List comprehension using various iterable
Below example describes how to apply different transformation functions on a given iterable.
#creating list of squares of natural numbers MyRange = range(1,6) NewList = [i*i for i in MyRange] print(NewList) #creating list of odd numbers MyTuple = (1, 2, 3, 4, 5, 6, 7, 8) NewList = [i for i in MyTuple if i%2!=0] print(NewList) #creating list of characters (in uppercase) of a string MyString = 'Hello' NewList = [i.upper() for i in MyString] print(NewList)
Output
[1, 4, 9, 16, 25] [1, 3, 5, 7] ['H', 'E', 'L', 'L', 'O']
List Comprehension and transformation function
In above examples, transformation function is defined inside the list comprehension syntax. Alternatively, it can be defined outside of it, which gives the user to create more innovative function.
Example: Create Grades using List Comprehension
In below example, a function called grade() is created which is used inside list comprehension syntax to categorize iterator's element.
def grade(x): if x < 0: return 'Invalid' elif x >= 0 and x < 30: return 'Fail' elif x >= 30 and x < 50: return 'Grade C' elif x >= 50 and x < 75: return 'Grade B' elif x >= 75 and x <= 100: return 'Grade A' else: return 'Invalid' MyList = [20, 45, 67, 90, -1, 89, 102] NewList = [grade(i) for i in MyList] print(NewList)
Output
['Fail', 'Grade C', 'Grade B', 'Grade A', 'Invalid', 'Grade A', 'Invalid']
Example: Find Prime Numbers using List Comprehension
A function called prime is created which is further applied on iterator using list comprehension technique to find out prime elements of the iterator. Please see the example below for more details.
def prime(x): i = 2 if x >= 2: count = 0 else: count = None while i <= x-1: if x%i==0: count = 1 break; i = i + 1 if count == 0: return x MyRange = range(1,20) NewList = [prime(i) for i in MyRange if prime(i) is not None] print(NewList)
Output
[2, 3, 5, 7, 11, 13, 17, 19]
Top comments (0)