Welcome to another chapter of our Python tutorial series. We will continue to discuss Python Lists in this post and have a look at Python List Comprehension in detail. Trust me, your knowledge of List Comprehensions will save a lot of time and make your code much cleaner. Without wasting much time, let us now dive deeper into the discussion.
Also, find here the link to all the chapters of Python: Learn Python
What is Python List Comprehension?
List comprehension in Python allows you to create lists from an iterable object like range, dictionary, tuple, set, or a list, based on a condition. If the condition mentioned while adding a list comprehension is satisfied in your code, the interpreter will create the list for you. It helps in making your code look much smaller and compact.
Let us now have a look at a normal way of creating a list of elements using a for loop.
cubes = []
for x in range(1,11):
cubes.append(x**3)
print(cubes)
Output
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
The code mentioned above can also be rewritten using List comprehensions as mentioned below.
cubes = [x**3 for x in range(1,11)]
print(cubes)
Output
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
You can notice that 4 lines of code have been reduced to only two lines. Moreover, only one line is required as we have added the print statement for your reference. You might not need that when you work on your real-time projects.
Let us look at a few more examples of code to understand more about the Python List Comprehensions.
PROGRAM TO ADD A NUMBER FROM A LIST WITH EACH ELEMENT FROM ANOTHER LIST
a = [11,22,33]
b = [10,20,30,40]
lst = [x+y for x in a for y in b]
print(lst)
Output
[21, 31, 41, 51, 32, 42, 52, 62, 43, 53, 63, 73]
PROGRAM TO CREATE A LIST WITH THE FIRST LETTER FROM A SET OF WORDS
words = ['Apple','Grapes','Banana','Orange']
list1 = [x[0] for x in words]
print(list1)
Output
['A', 'G', 'B', 'O']
We hope you have understood the concept of Python List Comprehensions. Please let us know your views in the comments section below.