List Comprehension

Introduction to List Comprehension

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

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

Let’s summarize what we have discussed previously-:

  1. How to create a 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 a 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 the variable from input to stored in a list as values
  3. input_set: values from input_set is used to store either after manipulating or simply storing the value in a list.

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

1.Simple list comprehension

Nested list using if statement

3.List inside list using the list comprehension


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

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

Keep enjoying!

 

Close Menu