Comprehension is a very powerful technique to make complicated things simple in Python.
This article will talk about list comprehensions, dictionary comprehensions, and set comprehensions in Python.
1. Python List Comprehension
Suppose, we want to separate the letters of the word Hello
and add the letters as items of a list.
We usually use a for loop to complete it:
a = []
for letter in 'Hello':
a.append(letter)
print(a) # => ['H', 'e', 'l', 'l', 'o']
List comprehension is an elegant way to define and create lists based on existing lists.
网友评论