Create Lists Easily with List Comprehensions

139次阅读
没有评论

In Python, you’ll often need to create a new list based on the items of an existing one. For example, imagine you want to create a list of the squares of numbers from 0 to 9.

The traditional way to do this involves creating an empty list, looping through the original sequence, performing an operation, and appending each new result to the list.

Python

# The traditional for-loop way
squares = []
for i in range(10):
  squares.append(i * i)

print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This code is clear and it works, but it’s a bit verbose for such a common task. Python, valuing conciseness and readability, offers a more elegant solution.

The Pythonic Way: List Comprehensions

A list comprehension allows you to build a list in a single, descriptive line of code. It combines the loop and the append operation into a compact and highly readable format.

Here is how you would create the same list of squares using a list comprehension:

Python

# The Pythonic list comprehension way
squares = [i * i for i in range(10)]

print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

How does it work?

Let’s break down the syntax [expression for item in iterable]:

  1. expression: This is what you want to do to each item (i * i).
  2. for item in iterable: This is the loop part, which iterates over a sequence (for i in range(10)).

The result is a new list, created based on the expression. You can even add a condition to it. For example, to get the squares of only the even numbers:

Python

even_squares = [i * i for i in range(10) if i % 2 == 0]
print(even_squares)
# Output: [0, 4, 16, 36, 64]

List comprehensions are a favorite feature among Python developers because they make code shorter, more efficient, and often easier to read once you understand the syntax. Give it a try! See you tomorrow.

正文完
 0
评论(没有评论)
验证码