# Python list comprehension

List comprehension is one of the most most distinctive feature in Python , which you can use to create powerful functionality within a single line of code . It is an elegant way to define and create lists based on existing lists. Essentially, it is Python's way of implementing a well-known notation for sets as used by mathematicians.

As list comprehensions return lists, they consist of brackets containing the expression followed by a for clause, which is executed for each element along with the for loop to iterate over each element. The expressions can be anything, meaning you can put in all kinds of objects in lists. Syntax
[expr for element in list if condition]

This is equivalent to Python for loop:

for item in list: if conditional: expression
example

The following code will create List using List Comprehension.

>>> lst = [x for x in range(5)] >>> print (lst) [0, 1, 2, 3, 4]

## Python list comprehension exercises

Create a list of squares using List Comprehension.

>>>lst = [] >>>lst = [x**2 for x in range(10)] >>>print(lst) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The above code is equivalent to:

lst = [] for x in range(10): lst.append(x**2) print(lst)

## Using Conditionals in List Comprehension

### if statement in List comprehension

List comprehension is an example of the language's support for functional programming concepts . You can modify the existing list using conditional statements in List comprehension .
>>>lst = [ x for x in range(100) if x % 10 == 0] >>>print(lst) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

The above code is equivalent to:

lst = [] for x in range(100): if x % 10 == 0: lst.append(x) print(lst)

### if..else ststement in List comprehension

Here we have a list containing numbers 1 to 10. If the item in list less than or equal to 5 then the number is added to 10 and if the number is greater than 5 then the item is added to 100.

>>>lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>lst= [x+10 if x <= 5 else x+100 for x in lst] >>>print(lst) [11, 12, 13, 14, 15, 106, 107, 108, 109, 110]

### List comprehension with multiple if's (nested if)

Following Python script produces the integers between 11 and 19, inclusive.
>>>lst = [i for i in range(30) if i > 10 if i < 20] >>>print(lst) [11, 12, 13, 14, 15, 16, 17, 18, 19]

The above code is equivalent to:

lst = [] for i in range(100): if i > 10: if i < 20: lst.append(i) print(lst)

## Nested List Comprehensions

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4 as "Name", "Marks" and "Grade".
lstMx = [ ['John', 'Gates', 'Don', 'Bill'], #Name [82, 55, 71, 42], #Marks ['A', 'C', 'B', 'D'], #Grade ]
You can use the following list comprehension will transpose rows and columns:
>>>lst = [[row[i] for row in lstMx] for i in range(4)] >>>print(lst)
output
[['John', 82, 'A'], ['Gates', 55, 'C'], ['Don', 71, 'B'], ['Bill', 42, 'D']]

The above code is equivalent to:

lst = [] for i in range(4): rLst = [] for row in lstMx: rLst.append(row[i]) lst.append(rLst) print(lst)

## Python list comprehension in functions

Python's list comprehension is an example of the language's support for functional programming concepts . Letss see how you can use list comprehension in functions.
>>> def findSquare (x): ... return x*x ... >>> lst = [findSquare(i) for i in range(5)] >>> print(lst) [0, 1, 4, 9, 16] >>>

## How to read a file line-by-line using List Comprehension

Create a text file and add some content and save its as "testfile.txt".

filename = "testfile.txt" with open(filename) as f: lst = [x.strip() for x in f] print(lst)

### Upper case using List Comprehension

>>> lst = [x.upper() for x in ["apple","banana","cat"]] >>> print(lst) ['APPLE', 'BANANA', 'CAT'] >>>

### Lower case using List Comprehension

>>> lst = [x.lower() for x in ['APPLE', 'BANANA', 'CAT']] >>> print(lst) ['apple', 'banana', 'cat'] >>>

## List Comprehensions Vs Map and Lambda functions

List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce() . Unless you're applying a single-argument function, list comprehensions are clearer than the map built-in function for simple cases.
lst = [] for x in range(5): lst.append(x**2) print(lst)
output
[0, 1, 4, 9, 16]

### Using map() with lambda

>>> list(map(lambda x: x**2, range(5))) [0, 1, 4, 9, 16]

### Using List Comprehension

>>> [x**2 for x in range(5)] [0, 1, 4, 9, 16]