3 ms·
I usually break list comprehensions before the 'for', and then again before the 'if' if they still need it. No backslashes. Implicit line continuation works as
by BrandonM 18y ago
I usually break list comprehensions before the 'for', and then again before the 'if' if they still need it. No backslashes. Implicit line continuation works as well within list comprehensions as it does in function calls.
Wow, I learned more from this comment than I did from the entire wiki page. I wonder why I never realized this before... I tend to break my list comprehensions the same way, and for some reason I thought the backslashes were necessary.
if any(number < 10 for number in numbers):
Very nice. I need to start using some of these builtins a little more. In particular, I'm pretty sure that I've used
for foo, index in izip(list, count())
before instead of simply using enumerate. any is one that I'll definitely have to keep in mind.
- globalrev 18y agoexcept it is not working? >>> numbers = [1,10,100,1000,10000,100000,1000000] >>> if any(number < 10 for number in numbers):print number Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> if any(number < 10 for number in numbers):print number NameError: name 'number' is not defined >>> if any(number < 10 for number in numbers): print number Traceback (most recent call last): File "<pyshell#7>", line 2, in <module> print number NameError: name 'number' is not defined >>>
- jcl 18y agoIt is working; the variable "number" is local to the generator expression and can't be used in the print statement. It works if you print something else instead (e.g. "Success!" in the article). If you just want to print the numbers less than 10, it's easier to do: print [number for number in numbers if number < 10] or print '\n'.join(str(number) for number in numbers if number < 10) if you want the same formatting.
- yourmomis1337 18y agoif any(number < 10 for number in numbers): Okay this is has to be the best way to do this, much better than the example in the article.