Python’s List Comprehensions

SedatParlak
3 min readOct 9, 2022

--

Lists are the most common data type for developers in any programming language. When you are coding you generally need to work with lists such as working on existing lists or creating new ones. At its simplest, list comprehension is the easiest way to create a new list from an existing one.

Reference: https://buggyprogrammer.com/

Output, for loop, and condition are components of a list comprehension as you can see above. Also, you can create a list comprehension without conditions.

The advantages of list comprehension are:

  • Less code
  • More readable
  • Faster than for loops
  • Does not need append() method

Basic Examples of List Comprehensions

Example 1: Simple list comprehension without conditions.

Example 2: You can use math operations for each list element:

Example 3: List comprehension with conditions.

We can add an ‘if’ condition for filtering the data to our list comprehensions. Without the ‘else’ statement ‘if’ condition should be on the right side of for loop in the code line.

Example 4: If we need more than one ‘if’ statement:

Example 5: But if we use the ‘if’ and ‘else’ statements together, conditions should be on the left side of the for loop in the code line. Check out the below examples.

Example 6: List comprehension with nested loops.

Example 7: We may freely use methods and functions in our list comprehensions like these:

Conclusion

Mastering about list comprehension make our code more efficient, faster and shorter. We should use list comprehension to basic filtering or, to easily create a list and work on it. However, we should avoid use list comprehension with too many conditions. It makes our code more complex and unreadable. Also, we shouldn’t forget that every list comprehension can be written with for loops but every for loops can’t be written with list comprehension.

github : https://github.com/SedatParlak

linkedln: https://www.linkedin.com/in/sedat-parlak-0b7013131/

--

--