DEV Community

Jonathan
Jonathan

Posted on • Originally published at dev.corteso.com on

List comprehension in Python

What are list comprehension ?

It’s a feature of the Python language allowing to do many things like :

  • Create a list in a concise way

  • Filter list items

  • Editing list items

Structure

The structure of a list comprehension is quite simple. You start by writing an expression , followed by a for clause, and end with one or more if clauses.

Examples

For this example I will use the following list:

characters = ['Harry', None, 'Ron', False, 'Hermione']
Enter fullscreen mode Exit fullscreen mode

Here I will use a list comprehension for two things:

  • Removing the "False" and "None" items from the list
  • Adding the word "Hello" in front of each name

If I wrote this in another language, I would probably write something like this:

sorted_names = []
for character in characters:
  if(character):
    sorted_names.append('Hello %s' % character) print(sorted_names)
Enter fullscreen mode Exit fullscreen mode

Here is now a list comprehension that allows to reach exactly the same result:

sorted_names = ['Hello %s' % character for character in characters if character]
print(sorted_names)
Enter fullscreen mode Exit fullscreen mode

The resulting code is much more concise and easier to read. At least it is when you separate the different parts.

In the previous example, list comprehension starts with the expression to add the word "Hello" in front of each name:

'Hello %s' % character
Enter fullscreen mode Exit fullscreen mode

We will then indicate the elements on which we will work (as in the for loop in the longer example):

for character in characters
Enter fullscreen mode Exit fullscreen mode

We end with the part allowing to filter the elements of the list. In this case, we will only execute the first expression if character is different from "False" and "None":

if character
Enter fullscreen mode Exit fullscreen mode

Once these elements are assembled and put in square brackets, we get the list comprehension seen previously.

It should also be noted that a list comprehension does not modify the original list, which is why I assign it to a new variable.

Conclusion

As this short example shows, list comprehension is a powerful element of the Python language.

But be careful not to use it for everything and nothing! Some methods such as map also allow to modify the content of a Python list and may, in some cases, be more suitable than list comprehension.

I hope you enjoyed this article! Feel free to share it on social networks !

Top comments (0)