I have quite a bit of trouble with list comprehension. Usually, I can get the hang of it eventually. Eventually.
My brain has a much greater penchant for classic for loops. List comprehension can get a little sneaky in the following ways:
1) "for"s in all the wrong places - getting a grip on which parenthesizes a for should be within and which ones it should sit outside of is a little tricky at first
2) sometimes you shouldn't use them at all - you have to know what you have, and what you want. List comprehension only really works when you're going from an iterable, to generating a list
3) surprise generator functions! - this is a problem I keep running into. especially when trying to juggle recursion and list comprehension at the same time. If the recursive pieces aren't all perfect, a generator function is sometimes passed into somewhere it shouldn't be. I'm not always sure what that means, let alone how to fix it.
All in all though, elegance and increased efficiency make it worthwhile to figure out ways around these tricky bits, and use list comprehensions.
This comment has been removed by the author.
ReplyDeleteA generator function, from the outside, is just an iterator, i.e. it has a __next__ method, and is not subscriptable (no indexing, only sequential access). The cool thing about the generator construct in python is that you can write a *function* using a "yield" statement instead of a return statement, and that function will return an iterator where each call to __next__ jumps to the next yield statement in the function.
ReplyDelete>>> def range(a, b):
... i = a
... while i < b:
... yield i
... i += 1
(Blogspot comments apparently remove sequential whitespace characters, so my python code looks awful)
ReplyDeleteThis comment has been removed by the author.
ReplyDelete