List Comprehension in Python

List comprehension is one of method to create lists by doing some specific operations on each member of a Sequence. Here sequence can be String, List itself or tuple.
List comprehension consists of brackets containing an expression followed by a for clause then none or more for or if clause. For example – [x**3 for x in range(4)] is a List Comprehension which will evaluate to list [1, 8, 27].

Examples of List Comprehensions in Python

squares = [x**2 for x in range(4)]
squares        
# Returns [1, 4, 9]


cubes = [x**3 for x in range(4)]
cubes 		   
# Returns [1, 8, 27]

Filtering a list using List Comprehension

You can use List Comprehension to filter values from a list. Like if you have some list containing unwanted values then you can easily through those out of list just using one line of code(List Comprehension).

alist = [1, -29, 91, 37, -3]
y = [i for i in alist if i >= 0]
y
# Returns list [1, 91, 37] Just containing positive values

Applying a Function to all elements of Sequence using List Comprehension

List Comprehension can be used for passing all elements of a list to a function one-by-one and making a new list from values returned by function.

alist = [82, 29, -12, 10, -4]
y = [abs(alist) for i in alist]
y 
# Returns [82, 29, 12, 10, 4] list only containing absolute(abs) values

Making List of Tuples using List Comprehension

List Comprehension can also be used for making list of tuples which is a list of paired values like [ (a, b), (x, y), …. ….. ….. ]

[(x, x**2) for x in range(3)]
// Returns [(0, 0), (1, 1), (2, 4)] 

Creating Nested Lists using List Comprehension

List Comprehension can also be used for creating Nested Lists – Lists inside list.

[[x, x**2] for x in range(3)]
[[0, 0], [1, 1], [2, 4]]

Flattening Nested Lists using List Comprehension

Nested lists are those lists which have lists as their elements. For example – [ [1, 3], 73, 29 ] is a nested list.

x = [[1,2,3], [4,5,6], [7,8,9]]
[num for i in x for j in i]
# Returns [1,2,3,4,5,6,7,8,9]

Other Stuff about List Comprehensions in Python

Josh

Hi, I'm Josh a Computer Science graduate from California State University, Sacramento since coming out with my Master's from university. I've worked with multiple startups across US and in UK as well primarily as a Python Developer. Here on this website, I'm sharing my knowledge of Python. If you want to ask me anything about Python feel free to reach out, I would be happy to help you out.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts