4 ms·
Now I don't like neither example. The second one isn't declarative. Python actually has preferred, declarative way to write this kind of code — just use generat
by deno 17y ago
Now I don't like neither example. The second one isn't declarative. Python actually has preferred, declarative way to write this kind of code — just use generators.
How much more clearer is this code:
def some_func(someList):
for elem in someList:
# do something with elem
yield elem
- endtime 17y agoIsn't the "generative" approach a bit more limited? It works if all you want to do is iterate through the result once, but if you want to do anything more than that with it you'll need a list. No?
- deno 17y agoIt depends on the situation, I guess. You can “cache” specific results inside generator object/function and still return generator. If your result is something one can iterate over you should return generator. If you then need list you can just convert your generator into one. If your list is actually some kind of data structure than perhaps a more object-oriented approach is suitable? Python is not functional language after all. But if all you need is to iterate more than once over generator you can just cache it as a list and reuse if needed.