List comprehension is one of Python’s most unique features; it allows you to generate complex functionality in a single line of code. Nevertheless, many developers find it challenging to utilize list comprehension’s more sophisticated features in Python. Some programmers utilize them excessively, which might result in less effective code and more difficulty in comprehending.
You can learn everything you need to know about Python list comprehension from this article, including how list comprehension differs from for loop comprehension, how to use conditionals in list comprehension, how to use nested lists in list comprehension, and much more.
Python List Comprehension : What Is It?
Several programming languages provide a syntactic feature known as list comprehension to create lists based on preexisting lists. One such language is Python. Put differently, list comprehensions are employed in the creation of new lists from other iterables or the conversion of existing lists into new lists.
Comprehension of a list includes:
- Sequence of input
- A variable used to hold the input sequence’s members
- Expression of the predicate
- output expression that both satisfies the predicate and generates the output list based on the input sequence. Check out the Python Training in Pune..
List Comprehension Python vs For Loop in Python
The first method we use when we want to repeat a block of code a certain number of times is to use “for loops.” List comprehensions are more compact than for loops so they can accomplish the same task more effectively than the latter. As such, it offers an excellent substitute for loops.
Here, let’s look at an example. Let’s say we wish to separate a word’s letters and compile a list of those letters.
If you were to use a for loop, the code block for the same would be:
letters = []
for letter in ‘technology’:
letters.append(letter)
print(letters)
Output:
1
[ ‘t’, ‘e’, ‘c’, ‘h’,’n’, ‘o’, ‘l’, ‘o’, ‘g’, ‘y’]
As demonstrated below, we can use List Comprehension to achieve the same outcome with less code lines:
letters = [ letter for letter in ‘technology’ ]
print(letters)
Output:
1
[ ‘t’, ‘e’, ‘c’, ‘h’,’n’, ‘o’, ‘l’, ‘o’, ‘g’, ‘y’]
When using Python list comprehensions, you don’t always require a list to produce another. List comprehension will recognize it as a string and treat it as a list if we utilize strings. Technology is a string, not a list, in the list comprehension code block example above.Expand your expertise with our Python Web Development Course, designed to deepen your knowledge and enhance your skills.
Are you looking after Career Guidance from Experts?
Want Free Career Counseling?
Just fill in your details, and one of our expert will call you !
List Comprehension Python vs Python Lambda functions
L lambda functions and list comprehensions are two robust Python tools for creating and working with lists.The ideal option for every given task will depend on the details, as each has its own set of pros and cons.
A brief method of generating new lists from preexisting lists is through list comprehensions. They frequently operate more quickly than other techniques like map() and filter(). List comprehensions, however, can be challenging to read and comprehend, mainly when dealing with complex phrases.
An example of a list comprehension might be this:
Python
numbers = [1, 2, 3, 4, 5]
squared_numbers = [number ** 2 for number in numbers]
print(squared_numbers)
Proceed with caution when using the code. Find out more
The squares of the integers in the original list of numbers are created by this code and added to a new list called squared_numbers. Although the list comprehension is clear and concise, complex expressions enclosed in square brackets may be challenging to understand.
Anonymous functions called lambda functions come pretty handy for simple calculations. They frequently work in tandem with list comprehensions to produce increasingly intricate phrases. Although lambda functions can be slower than list comprehensions, they are more straightforward to read and comprehend.
An instance of a lambda function is as follows:
Python
square_function = lambda number: number ** 2
squared_numbers = [square_function(number) for number in numbers]
print(squared_numbers)
Use cautious when utilizing the code. Learn more
This code generates the square_function lambda function, which accepts an integer as input and returns the square of that number. Although the lambda function is more straightforward to read and comprehend than list comprehension in the preceding example, it operates more slowly.
List comprehensions are often a better option for straightforward jobs, but lambda functions are better for more complicated tasks. The ideal choice, though, will always rely on the particulars of the assignment.
● Map() with Lambda Function
First, let’s look at how to work with lists using map() and the Lambda function:
letters = list(map(lambda x: x, ‘technology’))
print(letters)
The code above creates a list of the letters in the string “technology,” separated by commas, using the map() function with lambda. The letters are the list’s name.
Output:
[ ‘t’, ‘e’, ‘c’, ‘h’,’n’, ‘o’, ‘l’, ‘o’, ‘g’, ‘y’]
We can use Python List Comprehensions to get the same outcome. Additionally, comprehension codes are more straightforward and understandable to humans.
To write the corresponding Python List comprehension function, follow these steps:
- Once the new list has been named, begin using the square brackets.
- Add the variable name (or, in our case, the string) that we will use to loop through each element of the previous list.
- To repeat the sequence element—our variable—add the for clause.
- Indicate the source of the variable. Put the sequence from which we shall obtain our variable after the in keyword. In this instance, we’ll modify the components of our new list using the technology string.
Thus, the following is how the finished Python List Comprehension code looks:
New_list=[ x for x in ‘technology’]
print(new_list)
Output:
[ ‘t’, ‘e’, ‘c’, ‘h’,’n’, ‘o’, ‘l’, ‘o’, ‘g’, ‘y’]
Looking forward to becoming a Python Developer? Then get certified with Python Online Training
Take Action! Book a Free Expert Session
Get Free Career Counseling from Experts !
● Filter() with Lambda Function
Now that you know how to use lambda to replace the map() method with Python list comprehension, it’s time to look at how to do the same thing with the filter() function.
Here, we have used filter() with lambda to remove any values that aren’t even from an existing list, and then we have stored the resulting values in a new list.
list1 = [1,2,3,4,5,6,7,8,9,10]
list1 = list(map(int, list1))
new_list= filter(lambda x: x%2, list1)
print(list(new_list))
Output:
[1, 3, 5, 7, 9]
See below for an example of how Python List Comprehension might achieve the same result:
list1 = [1,2,3,4,5,6,7,8,9,10]
print(list1)
new_list = [ x for x in list1 if x%2 ]
print(new_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 3, 5, 7, 9]
Claim your free expert counseling session today!
Do you want to book a FREE Demo Session?
● Reduce() with Lambda Function
As mentioned before, we can utilize Python list comprehensions with the reduce() function to create shorter and more effective lambda function codes.
The code block that follows is an illustration of how to use lambda with reduce():
from functools import reduce
list1 = [1,2,3,4,5,6]
new_list = reduce(lambda x,y: x+y, list1)
print(new_list)
Note: Importing the reduction module from functools is necessary for Python 3 users, as seen in the code block above, due to the module’s recent relocation to the functools package.
After adding all the lists, the first one appears in the output.
Output:
21
Python list comprehensions can produce the same outcome, as demonstrated below:
Note: Y cannot be used in this situation since Python list comprehensions only support one variable. Therefore, we can utilize an aggregation function like sum() to complete the work.
list1 = [1,2,3,4,5,6]
new_list = sum([x for x in list1])
print(new_list)
Output:
21
Note: Here, we didn’t need to import the reduced module because we used Python list comprehension instead. .Learn more at Full Stack Online Course
Connect with industry experts and get all your questions answered!
Meet the industry person, to clear your doubts !
Conditionals in Python List Comprehension
Conditional statements are another valuable tool for manipulating and changing lists in list comprehensions. With the aid of some examples, let’s discover how to accomplish that. Here, the range we wish to use in our examples is defined by the mathematical function range(). It accepts a single integer as an input, and its range is defined as follows: 0 to one less than the argument. Range(20), for instance, will take into account the range of values from 0 to
Examples:
1.Using the if statement for list comprehension in Python
new_list = [x for x range(20) if x%2==0]
print(new_list)
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
2. Using Python List Comprehension with Nested IF
new_list = [x for x in range(50) if x %2==0 if x%5==0]
Output:
[0, 10, 20, 30, 40, 50]
The preceding example shows how list comprehension works. It checks if x is divisible by 2 first. If so, it moves on to the other conditional expression, which determines whether the x that was determined to be divisible by 2 is also divisible by 5.
Only if both requirements are satisfied is x added to the list new_list.
3. Utilizing an if-else statement and list comprehension in Python
even_odd = [f”{x} is even” if x%2==0 else f”{x} is odd” for x in range (10)]
print(even_odd)
Output:
[‘0 is even’, ‘1 is odd’, ‘2 is even’, ‘3 is odd’, ‘4 is even’, ‘5 is odd’, ‘6 is even’, ‘7 is odd’, ‘8 is even’, ‘9 is odd’]
The above example’s list comprehension verifies every number between 0 and 9. The phrase “x is even”—where x is the corresponding number—is added to the even_odd list if it is determined that x is divisible by 2. Whenever a condition is unsatisfied, the code adds the phrase “x is odd,” followed by the correct integer, to the even_odd list and runs the else line. Enroll in the Data Analyst course in Pune to master Data Analytics.
Want to Book A Free Expert Guidance Session?
Get FREE career counselling from Experts !
Nested Lists in Python List Comprehension
When we discuss implementing nested lists, nested loops are the first thing that comes to mind. Naturally, as we’ve already demonstrated about loop replacements, nested loops may also be handled with Python list comprehension. With the aid of an example, let’s learn how to accomplish that.
When multiplying, it’s conceivable that we’d prefer to view the tables for 4, 5, and 6. By constructing the following code block using standard nested for loops, we may get the same result:
for x in range(4,7):
for y in range(1,11):
print(f”{x}*{y}={x*y}”)
The output would be:
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
4*10=40
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
6*1=6
6*2=12
6*3=18
6*4=24
6*5=30
6*6=36
6*7=42
6*8=48
6*9=54
6*10=60
Use the following code block with Python’s list comprehension to do the same thing:
table = [[x*y for y in range(1,11)] for x in range(4,7)]
print(table)
Output:
[[4, 8, 12, 16, 20, 24, 28, 32, 36, 40], [5, 10, 15, 20, 25, 30, 35, 40, 45, 50], [6, 12, 18, 24, 30, 36, 42, 48, 54, 60]]
The preceding example uses the “for loop” using y as the internal variable.
Key Takeaways
A neat approach to defining and building lists from existing lists is Python’s list comprehension.
Python list comprehensions are faster and more compact than loops and other lambda methods like map(), filter(), and reduce() when constructing lists.
While it is possible to rewrite any Python list comprehension as a for loop, not all complex for loops are amenable to this transformation.
The compactness and readability of Python list comprehensions lead many to believe they are more intrinsically Pythonic.
If you want your code to remain user-friendly, you shouldn’t write extremely lengthy list comprehensions on a single line.To master the skills from industry experts at 3RI Technologies.
Secure your personalized career counseling session today!
Book Your Time-slot for Counselling !
The Bottom Line
The results show that list comprehensions in Python are more efficient and easier to use than lambda functions and for loops. Python list comprehensions are an excellent substitute for loops and lambdas because of their speed and readability. Mastering this understanding can help us write shorter, faster, and more effective codes. There is much more to learn about Python, even though we have covered all the significant subjects and provided examples.
Do you want to study with current materials and acquire in-depth knowledge? Take a look at 3RI Technologies’ organized Python Certification Training Course. I will be able to learn all of Python’s primary modules and packages, web scraping tools, lambda functions, and more with the help of this course. Using Hadoop and other Big Data platforms, this course will show you how to code in Python. You will also receive numerous practical exercises to help you become proficient in Python.