List comprehension





Hello folks....!!!!!!
Today we will look into the concepts of list comprehension. 

List comprehension

The list comprehensions are used to build a list from an existing iterable. The general syntax is :

li=[variable,for loop,if-condition]

The if condition is optional one. The variable here denotes the loop control variable. You can understand it better when explained with examples. Let us look at some examples:

Example 1: Without if condition

list comprehension python

The general format of the above snippet is :

list comprehension in python

Instead of writing these many lines, One can combine all these steps and write in one line using list comprehension syntax. Here, a list is formed from another iterable- a "String".

Example 2: With if condition

In the Example 1, the space is also considered as an item in the list construction. Now let us use an if condition to remove it. Thus the code becomes :

List comprehension of python

Thus every item from the iterable is checked against space (" "). If it is not a space, it is added to the resultant list.

Example 3: Condition with iterables

The if-condition can be checked based on another iterable also. Consider a list of words. We want only the words with meaning in the resultant. Thus no 'is','was' or any other words without specific meaning should be considered. This can be done in list comprehension as given below:

List comprehension in python

Example 4: range() function

Instead of an iterable you can also use the range() function to use a sequence of numbers. For example:

Find the multiples of '2' between the numbers 1 and 10

List comprehension in python

Example 5: nested if-condition

The if-condition can be nested also. In such cases, the first if-condition evaluates to true, then the second if-condition is checked. Look at the example below:

Find the numbers between 1 and 50, that are divisible by both 3 and 5 :

List comprehension in python

Example 6: nested for loops:

The for loops can be nested in this list comprehension. They are executed like normal nested for-loops. For each iteration of the first loop the inner one is executed 'n' times. Look at the code snippet below:

List comprehension in python

This can be written in list comprehension as :

List comprehension in python



Next Topic👉

Comments