List Comprehension In Python

Boost Your Career with In-demand Skills - Start Now!

Python provides us with a unique and efficient way of creating lists. List comprehensions are widely used by ‘Pythonistas’ all over the world while coding lengthy programs.

List comprehension is a more concise way of creating lists than the traditional naive way. In this article, you’ll learn what list comprehensions are, how can we create them, and what all can be included in it. Also, we’ll see how list comprehension in python is a better choice than loops.

What is List Comprehension in Python?

Python has built-in support for creating lists using a more abbreviated syntax called the list comprehensions. List comprehensions provide us with a simple way to create lists with a more concise syntax.

The basic syntax of List comprehension is:
[output expression for element in iterable]

Let’s get a better understanding of the concept using an example.

Suppose we need to get a list of the squares of all numbers less than 10. The first thing that comes to our mind is to create an empty list and then append squares of the numbers to the list using for a loop. But to make this process more ‘Pythonic’, let’s create this list using List Comprehension.

squares = [x**2 for x in range(10)]
print(squares)

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

So, [x**2 for x in range(10)] forms our list comprehension. Let’s break it down.

  • To begin with, we write all the components of a list comprehension inside square brackets( [ and ] ). Because, well, we’re creating a list!
  • x**2 forms our output expression. The value of this expression becomes the element of our list.
  • x is the iteration variable. (Or as we say counter variable in looping)
  • range(10) is iterable that generates the value of x.

Easy right?

Python List Comprehension on strings

Since strings come under iterables too, we can perform list comprehensions based on strings. To get each character of a string and store them separately in a list, we perform list comprehension on that string.

For example, let us get each character from the string ‘PythonGeeks’ and append it to a list. All we have to do is,

my_list = [ i for i in ‘PythonGeeks’]
print(my_list)

Output:

[‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’, ‘G’, ‘e’, ‘e’ ‘k’, ‘s’]

This is particularly useful when you want to get an integer as an input from the user and perform some operation on each digit separately. Consider this short session on the Python shell.

num = input("enter: ")
enter: 1456
print(num)
'1456'
numlist = [int(i) for i in num]
print(numlist)
[1, 4, 5, 6]
sum_of_digits = sum([int(i) for i in num])
16

List comprehension in Python with conditional statements

We can use conditionals with our list comprehension to modify our list even further. Conditional statements allow us to filter the elements in our list based on some condition.

Let’s see an example.

Here, we are trying to create a list that contains all even numbers less than 50.

even_list = [i for i in range(50) if i % 2 == 0]
print(even_list)

Output:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]

Python List comprehension example with nested for loop

You can even nest the for loops in your list comprehension as and when you need it. What if you want to create a list of all possible user IDs containing a letter and then a digit. We can do this in a very concise way using list comprehension.

letter = 'abcdefghijklmnopqrstuvwxyz'
digit = '0123456789'
ids = [i+j for i in letter for j in digit]

Output:

[‘a0’, ‘a1’, ‘a2’, ‘a3’, ‘a4’, ‘a5’, ‘a6’, … , ‘z7’, ‘z8’, ‘z9’]

Python List Comprehension vs Loops

Let’s create the ids list from the above example using our traditional loop method.

letter = 'abcdefghijklmnopqrstuvwxyz'
digit = '0123456789'
ids = []
for i in letter:
  for j in digit:
    element = i+j
    ids.append(element)

This produces the same result as the previous example. But can you see the difference in the number of lines? The traditional looping method took 5 lines to do the task we did in 1 line using list comprehension.

The list comprehensions are also more computationally efficient than for a loop. It requires less space and time than a loop which makes it more favorable for Python programmers.

Making it Readable

List comprehension in python are capable of encapsulating multiple statements in one single line. But this introduces a drawback to list comprehensions. As the list comprehension gets more complex, it becomes less readable. But Python has got us covered! We can make our complex list comprehension more readable by writing it across multiple lines.

Let’s get all numbers less than 100 which are divisible by 2 as well as 5. Now create a list that says ‘small’ if the number is less than 55 or ‘big’ if greater.

mylist = ['small' if item < 55 else 'big' for item in range(100) if item % 2 == 0 if item % 5 == 0]
print(mylist)

Output:

[‘small’, ‘small’, ‘small’, ‘small’, ‘small’, ‘small’, ‘big’, ‘big’, ‘big’, ‘big’]

This same list of comprehension can be extended to multiple lines.

mylist = [
  'small' if item < 55 else 'big'
  for item in range(100)
  if item % 2 == 0
  if item % 5 == 0]
print(mylist)

This produces the same output as above but it is clearer and more readable.

Summary

In this article, we learned what list comprehension in python is and how we can use them to our advantage. Not only do they require fewer lines of code, but they are faster than traditional functions and loops. So whenever you find yourself writing lines of code to create a list, try replacing those lines with Python list comprehension.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


PythonGeeks Team

At PythonGeeks, our team provides comprehensive guides on Python programming, AI, Data Science, and machine learning. We are passionate about simplifying Python for coders of all levels, offering career-focused resources.

1 Response

  1. Rohith says:

    Very well explained.

Leave a Reply

Your email address will not be published. Required fields are marked *