Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use a List Comprehension to Generate a List

Python Use a List Comprehension to Generate a List

Document Object Reference Manual Python3 Examples

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:

Output result:


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

Document Object Reference Manual Python3 Examples