Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!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 −
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 −
Applying this, chars list can be constructed by the following statement −
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
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
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
It will produce the following output −
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.