Lesson 16: Python List Comprehension

List Comprehension is a super powerful tool that helps you make custom lists in very potent and practical ways.

Most programmers that get the hang of list comprehension appreciate List Comprehension syntax of Python.

Although it can seem a bit different in the beginning it’s not too difficult to learn. We will start from simple examples and build up List Comprehension in this lesson.

Function : n/a

This lesson doesn’t introduce a new function.

Used Where?

Python’s List Comprehension can be used to make new lists by extracting from other lists or iterables. The point of List Comprehension is it can replace many functions and statements in one simple line.

A simple List Comprehension line can equal map, filter, conditional statements (if else) and loops.


Let’s start with some basic examples.

Syntax do(s)

1) List comprehension is made inside the same brackets of a list: []

2) [i for i in list] is the usual syntax where first i is the element, second i is the iterator and list is your iterable.

Syntax don't(s)

1) na

Example 1

>>> lst = [1,2,3,4,5]
>>> lst2 = [i for i in lst]
>>> print(lst2
)

[1,2,3,4,5]

Simplest form of List Comprehension: [i for i in lst]

Example 2

>>> lst = [1,2,3,4,5]
>>> lst2 = [i+2 for i in lst]
>>> print(lst2
)

[3,4,5,6,7]

Only by adding +2 to the first i, we implement map function to the whole list.

Example 3: Squares

>>> lst = [1,2,3,4,5]
>>> lst2 = [i**2 for i in lst]
>>> print(lst2
)

[1,4,9,16,25]

And squares of each item in a new list.

Tips

1- You can also add conditional statements to your List Comprehension.

Simply type your statement to the end and List Comprehension will do the rest.

Let’s see some examples:

Example 4: Conditional Statement

>>> lst = [1,2,3,4,5,6,7,8,9]
>>> lst2 = [i**2 for i in lst if i<4]
>>> print(lst2
)

[1,4,9]

And squares of each item in a new list.

Example 5: Conditional Statement 2

>>> lst = [1,2,3,4,5,6,7,8,9]
>>> lst2 = [i**2 for i in lst if i**2<40]
>>> print(lst2
)

[1,4,9,25,36]

And squares of each item in a new list.

Advanced Concepts (Optional)

1- You can use List Comprehension with nested data as well. In fact it’s more fun.

Example

>>> lst = [(12, 100), (13, 100), (14, 200), (15, 200)]
>>> a = [i[0] for i in lst if i[1] > 100]

[14,15]

Lesson 17

Dict Comprehension