Make len() usable on a generator
3 Oct
2014
3 Oct
'14
3:09 p.m.
Hi! I have just come across some code counting a generator comprehension expression by doing len([foo for foo in bar if some_condition]) and I realized it might be better if we could just use len(foo for foo in bar if some_condition) as it would avoid a list allocation in memory. Another possibility is to write sum(1 for foo in bar if some_condition), but that is not optimal either as it generates a lot of intermediate additions which should not be needed. Sure, len(generator) might lead to an infinite loop but since sum(generator) is allowed in Python I see no reason why len(generator) isn't. What do you think ?
3456
Age (days ago)
3465
Last active (days ago)
38 comments
20 participants
participants (20)
-
Adam Jorgensen
-
Alexander Belopolsky
-
Andrew Barnert
-
Cathal Garvey
-
Chris Angelico
-
Guido van Rossum
-
Ian Cordasco
-
Joshua Landau
-
Mark Young
-
Nick Coghlan
-
random832@fastmail.us
-
Scott Dial
-
Skip Montanaro
-
Stefan Behnel
-
Stephen J. Turnbull
-
Steven D'Aprano
-
Terry Reedy
-
Thomas
-
Thomas Chaumeny
-
Todd