Everything You Need to Know About List Comprehension in Python

List comprehension in Python is a concise way of creating lists from the ones that already exist. It provides a shorter syntax to create new lists from existing lists and their values. Suppose there is a list of cars, and you want to segregate the vehicles that start with M. The first thing that might come to your mind is using a for loop. Let’s see it in action with the below example.

cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]

new_list = []

for i in cars:

  if "M" in i:

    new_list.append(i)

print(new_list)

Output:

ListComprehension_1

As you can see in the above example, you used for loop and append to create the new_list with only the car names starting with M. List comprehension in Python shortens this long process and allows you to create the new_list with just a single line of code. Let’s see how you can write the above code with Python list comprehension.

cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]

new_list = [i for i in cars if "M" in i]

print(new_list)

Output:

/ListComprehension_2.

As you can see, by using list comprehension in Python, you could shrink the three lines of the for loop code in a single line.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

Syntax of List Comprehension in Python

The syntax of Python list comprehension is:

[expression for item in iterable if condition == True]

In the syntax mentioned above, the condition is optional. If you include the condition, the new list will contain only the elements that meet the condition, as seen in the above example. If you omit the condition, the new list will contain all the items. It is useful to iterate through and segregate the letters of a string. Let’s look at an example for that, too.

new_letters = [ l for l in 'Simplilearn' ]

print( new_letters)

Output:

ListComprehension_3.

You would have noticed that Simplilearn is a string and not a list. This means that Python list comprehension has the power to identify string or tuple but still work on it as a list.

How List Comprehensions In Python Differs From Lambda Functions

Python also provides other ways to construct new lists from the existing ones, one of which is lambda functions. These functions are also sometimes referred to as anonymous functions as they are nameless. It declares them using the lambda keyword instead of the regular def keyword. Even lambda functions allow creating a new list in a single line of code. Here’s an example of using lambda functions instead of list comprehension in Python.

new_letters = list(map(lambda l: l, 'Simplilearn'))

print(new_letters)

Output:

/ListComprehension_4

The primary difference between Python list comprehension and lambda functions is that it is easier to understand and read than the latter. Thus, list comprehension in Python becomes a more favorable way of creating lists than lambda functions.

Understanding Conditionals in Python List Comprehension

Conditionals are nothing but the optional if conditions in the list comprehension that you have seen earlier. Now, look at another example that uses a conditional and the in-built range() function to create a new list with odd numbers from the existing list.

new_list = [ i for i in range(15) if i % 2 != 0]

print(new_list)

Output:

ListComprehension_5

You can also use nested conditionals, i.e., nested ifs and if...else, with list comprehension in Python. Let’s look at examples for that.

Example for Nested Conditionals

new_list = [x for x in range(100) if x % 2 == 0 if x % 3 == 0]

print(new_list)

Output:

ListComprehension_6

In the above code, the first condition checks if the remainder after dividing the number by 2 is 0 or not. The second condition checks if the remainder after dividing the number by 3 is 0. If it meets both conditions, it adds the number to the new_list.

FREE Data Science With Python Course

Start Learning Data Science with Python for FREEStart Learning
FREE Data Science With Python Course

Example for if...else Conditionals

Let’s head back to the car’s example and apply the if...else condition to it. In the below code, you will return all the cars except Maserati. When it is Maserati, you will replace it with Mahindra.

cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]

new_list = [i if i != "Maserati" else "Mahindra" for i in cars]

print(new_list)

Output:

ListComprehension_7

As you can see in the output, it has replaced Maserati with Mahindra on the list.

Nested Loops In List Comprehension In Python

You can also use nested for loops in Python list comprehension. Suppose you want to find transpose of a matrix, let’s see how it is done with the use of list comprehension in Python.

mat = [[11, 21], [12,22], [13,33], [14,44]]

transpose_output = [[row[x] for row in mat] for x in range(2)]

print (transpose_output)

Output:

ListComprehension_8

Here, you used the mat variable in the above code with a matrix of 4 rows and 2 columns. You then used the Python list comprehension to output the transpose. However, the nested for loops in list comprehension does not work similarly to regular for loops. In list comprehension, it executes the for loop defined latter, first. In the above code, “for x in range(2)” is executed before “row[x] for row in mat”.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Conclusion

In this article, you learned everything about list comprehension in Python. You can now easily create a new list from an existing list, string, or tuple. The shorthand code helps to make the overall program more readable and straightforward. A good and deep understanding of list comprehension in Python will be most helpful in data science, where you will work with a lot of lists and tables. 

If you are new to Python programming, you can refer to Simplilearn’s Python Tutorial for Beginners. Once you are done with the basics, you can opt for the Online Python Certification Course. The course provides a vast range of learning resources and hands-on experience to help you excel in the Python development field.

Have any questions for us? Feel free to leave them in the comments section below, and our experts will get back to you right away.

Happy learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.