List comprehensions provide elegant, concise ways to create, modify, and filter lists in Python.

They work similar to a for-loop, but in a much more Pythonic way.

How to write a list comprehension

Let’s take a look at how to write list comprehensions by comparing them to a for-loop. We’ll create a list that contains the values from 0–9 using the range() function:

# Method 1: For loop
for_loop_list = []
for i in range(10):
  for_loop_list.append(i)
  
# Method 2: List Comprehension
list_comprehension = [i for i in range(10)]

# Let's see if these are the same
print(for_loop_list == list_comprehension)

# Returns
True

We can see how much simpler it is to write the list comprehension, than to rely on a for-loop. Not only do we not need to initialize an empty list, we are able to reduce everything down to a single line of code!

Check out my image below to see how they work in a visual way:

Image for post

How to write a list comprehension. Source: Nik Piepenbreier

#data-science #coding #programming #software-development #python

4 Tips to Master Python List Comprehensions
8.10 GEEK