Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

documentation for lazy for-comprehensions in Python

It looks like this construct in Python is not lazy:

g1 = ["'"+x+"'" for x in f2]

and this one is:

g2 = ("'"+x+"'" for x in f2)

since g2 has a next() method and g1 does not.

Where is this documented? I can't seem to find the relevant page in the python docs, not sure what to look up.

like image 447
Jason S Avatar asked Feb 13 '26 22:02

Jason S


1 Answers

You are looking for list displays and generator expressions. The first form is called a "list comprehension", and is a specialized form of defining a list.

As for the second form, the generator expression, this is what the documentation has to say:

A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces.

like image 170
Martijn Pieters Avatar answered Feb 19 '26 01:02

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!