Python Use a List Comprehension to Generate a List
A list comprehension is a concise and powerful tool in Python for creating lists. It allows you to generate a list in a single line of code, usually more concise and efficient than using a traditional for loop.
Example
squares
=
[
x**
2
for
x
in
range
(
10
)
]
Code analysis:
x**2: This is the expression part of the list comprehension, representing the square operation on eachx.for x in range(10): This is the iteration part of the list comprehension, representingxtaking values from 0 to 9 in turn.- The entire list comprehension
[x**2 for x in range(10)]will generate a list containing the squares of 0 to 9.
Output result:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Python3 Examples