In This Article, We Will Learn About List Comprehension In Python.
In Python, list comprehension is a concise way to create a new list by applying an operation to each element in an existing list or iterable.
It is a syntactic construct that consists of an expression followed by a for clause and zero or more if clauses.
The basic syntax of list comprehension is as follows:
new_list = [expression for item in iterable]
Using List comprehension you don’t want to write three to five lines of code. you can simply write in one line of code for IF and For loop.
data = [1,2,3,4,5] result = [] # Simple for and if loop code for i in data: if(i < 3): result.append(i) # List Comprehension with for and if the loop print([i for i in data if i < 3])
The expression is the operation that is applied to each item in the iterable. The result of this operation is then added to the new list.
Here is an example of a simple list comprehension that squares each element in a list of numbers:
numbers = [10, 20, 30, 40, 50] squared_numbers = [x**2 for x in numbers] print(squared_numbers) # [100, 400, 900, 1600, 2500]
In this example, list comprehension takes each number from the numbers list squares it using the expression x**2, and adds it to the new list squared_numbers.
List comprehensions can also include and if clause to filter the items in the iterable:
words = ['the', 'code', 'hubs', 'vision'] short_words = [word for word in words if len(word) <= 4] print(short_words) # ['the', 'code', 'hubs']
In this example, the list comprehension only adds the word to the new list short_words if the length of the word is
I hope you’ll get impressed by this list comprehension features. So let’s start coding within the next blog. If you’ve got any questions regarding this blog, please let me know in the comments.