Example HTML page

List Comprehension

In this topic, I am going to explain about list comprehension in python with few examples. You might be wondered about the syntax that used in python programming. The other programming languages are not having this flexibility.

List Comprehensions provide an easiest way for creating new lists.

For example, i want to create a list of ’10’ elements range from ‘0’ to ’10’. One thing i can do here is, first i will create an empty list and will append the elements one after another using for loop.

#creating an empty list
my_list=[]

# appending the elements from 0 to 10
for i in range(0,11):
    my_list.append(i)

#printing the elements of the list
print(my_list)

The output of the program is something like this:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Is there any other alternative way to do the same task?

The answer is ‘yes’, with list comprehension it is very easy to create a list. It almost takes only a line of code. Type the following (first line)snippet in IDLE and run it.

>>> [i for i in range(0,11)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We can also store the result in to another variable and print the result.

res=[i for i in range(0,11)]
print(res)

The output of this program is similar to the one which we got in the earlier program.

In the above statement, we used the list comprehension. First let us see the syntax of this.

Syntax:

variable = [expression   for-clause  if-clause]

The list comprehension starts with a ‘[‘ and ‘]’ , meaning that the result is going to be a list. This syntax has three parts, there is no specific meaning for any color shown in the syntax. It is only for representation purpose.

expression  : What you want to do?

for-clause : from which you want to iterate and how many times?

if-clause : do you want all the elements or you want to filter any elements?

Now, divide the above line of code in to three parts. I have not added the if-clause.

Expression : adding element ‘i’ to the list

for -clause : range of elements from 0 to 10

Now, in the following example i am adding if-clause to add the even numbers in to the list from the range 0 to 10.

res=[i for i in range(0,11) if i%2==0]
print(res)

The output of the above program is something like this:

[0, 2, 4, 6, 8, 10]

Here, i am giving some more examples on list comprehensions. I hope that you that you will get more clarity once you practice all the examples given below. Each example of the list comprehension will give a list as output and you can do some other useful operations after getting the resultant list. I have shown the program along with the program output.

Read a list of numbers from one list and computer the square of each element and store the result in to another list.

numbers=[1,2,3,4,5,6,7]
squares=[i**2 for i in numbers]
print(squares)
[1, 4, 9, 16, 25, 36, 49]

Read a string and store each character in the string in to another list

str='sudhakar'
res=[i for i in str]
print(res)
[‘s’, ‘u’, ‘d’, ‘h’, ‘a’, ‘k’, ‘a’, ‘r’]

Read a string and the letters ‘a’ in to another list.

str='sudhakar'
res=[i for i in str if i=='a']
print(res)

[‘a’, ‘a’]

Print the numbers which are divisible by 3 and 5 in the given range (0,21)

res=[i for i in range(0,20) if i%3==0 if i%5==0]
print(res)
[0, 15]

Read a string and print only the numbers i.e. digits in to a separate list.

str1="This is sudhakar and contact me at 9985327199"
res=[i for i in str1 if i.isdigit()]
print(res)
[‘9’, ‘9’, ‘8’, ‘5’, ‘3’, ‘2’, ‘7’, ‘1’, ‘9’, ‘9’]

Read a list of strings and capitalize each string and store in another list.

list1=['sudhakar','binish','rathnam','jai','sowmya']
res=[word.capitalize() for word in list1]
print(res)

[‘Sudhakar’, ‘Binish’, ‘Rathnam’, ‘Jai’, ‘Sowmya’]

Printing the list of string, which are ends with letter ‘s’ from another list.

list1=['this','will','print','how','many','strings','ends','with','s']
res=[i for i in list1 if i.endswith('s')]
print(res)
[‘this’, ‘strings’, ‘ends’, ‘s’]

Similarly you can use with starswith() method to print the string which starts with a specific character.

The following program is something different with the above programs. It prints even or odd for each element in the list and print the result in a separate list.

numbers=[2,4,3,5,7,9,12,34,25,67]
res=["even" if i%2==0 else "odd" for i in numbers]
print(res)

[‘even’, ‘even’, ‘odd’, ‘odd’, ‘odd’, ‘odd’, ‘even’, ‘even’, ‘odd’, ‘odd’]

Transposing the elements of a two dimensional matrix

matrix = [[1, 2], [3,4], [5,6], [7,8]]
res = [[row[i] for row in matrix] for i in range(2)]
print (res)
[[1, 3, 5, 7], [2, 4, 6, 8]]

Using nested for loops

list1=[10,20,30]
list2=[40,50,60]
list3=[i+j for i in list1 for j in list2]
print(list3)
[50, 60, 70, 60, 70, 80, 70, 80, 90]

You can practice more examples from the following link:

Python Exercise 15

 

 

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest