List Comprehension

List Comprehension is a concise method to create list in Python 3.

This technique is commonly used when:

  • The list is a result of some operations applied to all its items

  • It is a made from another sequence/iterable data

  • The list is member of another list/sequence/iterable data that satisfies a certain condition

This is where the lambda function would be used, butโ€ฆ we will learn the other way for readability. We will definitely talk about lambda functions in our Functional Programming Unit

List Comprehension Example 1

We are to create a list which squares all the numbers from [0,10)

# Old Method
squares = []
for i in range(10):
    squares.append(i ** 2)

print('Our result: %s' % squares)
Our result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# List Comprehension

squares = [i**2 for i in range(10)]

print('Our new result: %s' % squares)

How Does it Work?

List comprehension consists of:

  • A Square Bracket containing an expression that describes the list

  • One or more For clause to explain its members

  • Then a zero or more if clauses depending on the complexity of the list

List Comprehension Example 2

Explanation:

List Comprehension Example 3

Explanation

Last updated