Python List Comprehension is one of the most used python list functions. The main aim of this syntax is creating a new list from th existing list according to a condition. For example, we can check a list of strings and if a certain characetr exist in any of this string, we can create a new list from this list.
Let’s do an example to show how can we use Python List Comprehension. BElow, in our python string example, we will create list2 from list1 and then we will print list2. Here, we will check if “a” exist in any of the members of existing list, list1.
The output of this List Comprehension example will be like below:
You can also check Python List Reverse Sorting
As you can see above, onlty the strings that include “a”, is attend as a member of the new list. Here, the expression that we write in list2 is important. Here, we are saying that take any member in list1 if it has “a” inside and put it as a member to new list, list2.
You can also watch the video of this lesson!
We can do this Python List Comprehansion with also numbers. Let’s check the below example for this code.
The loutput of this Python List Comprehension example will be:
With Python List Comprehension, we can also search for a certain word in any string or numeric lists. For example in the below string list thatb has 5 member, we will search for “dogs” and we will add the strings that includes “dogs” to the new list.
As you can see below, the otput of this python code will include only the strings that include “dogs” in the lists.
We can also use Python List Comprehension syntax without an existing list. Below, we will create a list with range function and a if condition. Here, willl check the numbers from 0 to 9 and if these numbers are smaller than 8 and higher than 2, we will create a list with these numbers.
Let’s show another example that will list the squares of the given number range and assign it to a new list.
The output of this python code will be:
Lastly, let’s do another example, that will lsit the letters of a string in a list. Below, we will create a new list with the letters of Aragorn.
The output of this Python List Comprehension example will be like below:
In this Python Programming lesson, we have seen how to do List Comprehension with different python list examples. You can do differetn eaxmple to learn comprehension of python lists. With these new example, you will learn the function of this systax better. And day by day, you can create more complex python code related with Python List Comprehension.