reading-notes

My reading notes journal for Code Fellows

View the Project on GitHub

Readings: Ten Thousand 3

List Comprehensions in Python

List comprehension is a powerful and concise method for creating lists in Python that becomes essential the more you work with lists, and lists of lists. To understand the list comprehension, imagine it like this: you’re going to perform an expression on each item in the list. The expression will determine what item is eventually stored in the output list. Not only can you perform expressions on an entire list in a single line of code, but, as we’ll see later, it’s possible to add conditional statements in the form of filters, which allows for more precision in the way lists are handled.

Example 1: Creating a list with list comprehensions

construct a basic list using range() and list comprehensions
syntax
[ expression for item in list ]
digits = [x for x in range(10)]

print(digits)


Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We’re using the range() method to generate a list of numbers. Python iterates(or loops) through each item in that range, and saves a copy of the item in a new list called digits.

Example 2: Comparing list creation methods in Python

First, create a list and loop through it. Add an expression, in this example, we’ll raise x to the power of 2.

create a list using a for loop
squares = []

for x in range(10):
    # raise x to the power of 2
    squares.append(x**2)

print(squares)

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

Output

The same thing can be done using a list comprehension, but with a fraction of the code. Let’s take a look at how to create a list of squares using the list comprehension method.

create a list using list comprehension
squares = [x**2 for x in range(10)]

print(squares)

Even in this basic example, it’s obvious that list comprehensions reduce the code necessary to complete rather complicated task when working with a list.

Cited from: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

REFERENCES

https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

https://www.pythonpodcast.com/pysnooper-python-debugging-episode-241/