black and gray laptop computer turned on doing computer codes
Photo by Christina Morillo on Pexels.com

People coming from languages such as Java or C++ to Python may have been used to write many lines to do something that can be done in just one line in Python.

One such thing is list comprehension which is about the opportunity to compress many commands that can be used to manipulate list elements in just one line.

Let’s take an example.

Let’s say that we have the following list:

Now let’s say that we want to save only the odd numbers that are in that list.

One solution that can be seen in many other languages is the following:

Another potentially solution for that could be the following:

Now with list comprehension we could simply write this in one line:

I do agree that sometimes it can be a little bit messy to write everything in just one line. especially for your colleagues, who may have a hard time understanding your code.

Still, this Python feature is worth using from time to time, which can make your code look prettier.