Introduction to List Comprehension

In the series of Intermediate python next we are going to cover List Comprehension which is most wonderful, powerful operation for creating a list.

As, basics of list is already covered in “Getting started with Python“. If you want to go through the basics of list you can go to this link.

Let’s summarize what we have discussed previously-:

  1. How to create list and how to access its element
  2. Is list mutable or immutable?
  3. List are heterogeneous in nature.

Now, will go to some easy way of creating list using List Comprehension.

First I would like to tell you the syntax of list comprehension -:

Syntax:    list_name = [expression(variable)  for variable in input_set]

Here,

  1. list name: Created list name
  2. expression(variable): expression using variable from input to stored in list as values
  3. input_set: values from input_set is used to stored either after manipulating or simply storing the value in list.

We can aslo do the nested list comprehension, will check through the example.

1.Simple list comprehension

In [13]:
squares = [i*i for i in range(0,5)]
In [14]:
squares
Out[14]:
[0, 1, 4, 9, 16]
 

2.Nested list

In [16]:
nested = [y for x in [1,2,3,4,5] for y in [2,3,4]]
In [17]:
nested
Out[17]:
[2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4]
 

See same results using these 4 lines of code. It makes you clear how nested list is working

In [23]:
l = []
for i in range(1,6):
    for j in range(2,5):
        l.append(j)
        
print(l)
 
[2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4]
 

Nested list using if statement

In [18]:
nested = [y for x in [1,2,3,4,5] for y in [2,3,4] if y>=3]
In [19]:
nested
Out[19]:
[3, 4, 3, 4, 3, 4, 3, 4, 3, 4]
 

See same results using these 4 lines of code. It makes you clear how a nested list with if statement is working

In [22]:
l1 = []
for i in range(1,6):
    for j in range(2,5):
        if j>=3:
            l1.append(j)
        
print(l1)
 
[3, 4, 3, 4, 3, 4, 3, 4, 3, 4]
 

3.List inside list using the list comprehension

In [24]:
nested_list = [[i for i in range(1,5)] for j in range(2,5) ]
In [25]:
nested_list
Out[25]:
 
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

So, hope you are cleared with how to create list using list comprehension with if statement, nested list as well.

Stay tuned! More informative tutorials on intermediate python is on the way.

Keep enjoying!