Course
List Comprehension
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
List Comprehension
List comprehension is a very powerful programming tool. It is similar to set builder notation in mathematics. It is a concise way to create new list by performing some kind of process on each item on existing list. List comprehension is considerably faster than processing a list by for loop.
Example 1
Suppose we want to separate each letter in a string and put all non-vowel letters in a list object. We can do it by a for loop as shown below −
chars=[]for ch in 'TutorialsPoint': if ch not in 'aeiou': chars.append(ch)print (chars)
The chars list object is displayed as follows
['T', 't', 'r', 'l', 's', 'P', 'n', 't']
List Comprehension Technique
We can easily get the same result by a list comprehension technique. A general usage of list comprehension is as follows −
listObj = [x for x in iterable]
Applying this, chars list can be constructed by the following statement
chars = [ char for char in 'TutorialsPoint' if char not in 'aeiou']print (chars)
The chars list will be displayed as before
['T', 't', 'r', 'l', 's', 'P', 'n', 't']
Example 2
The following example uses list comprehension to build a list of squares of numbers between 1 to 10
squares = [x*x for x in range(1,11)]print (squares)
The squares list object is
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Nested Loops in List Comprehension
In the following example, all combinations of items from two lists in the form of a tuple are added in a third list object.
Example 3
list1=[1,2,3]list2=[4,5,6]CombLst=[(x,y) for x in list1 for y in list2]print (CombLst)
It will produce the following output
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
Condition in List Comprehension
The following statement will create a list of all even numbers between 1 to 20.
Example 4
list1=[x for x in range(1,21) if x%2==0]print (list1)
It will produce the following output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.