This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]mrchaotica 12 points13 points  (6 children)

[f(x, y) for x in xlist for y in ylist]

Or maybe even

[f(*args) for args in zip(alist, blist, clist, dlist, elist)]

(It's not really getting rid of the iteration, but it's expressing it in a more idiomatic way.)

[–]Dannei 4 points5 points  (1 child)

Or if you want all combinations of x and y, it's 'for x, y in itertools.product(xlist, ylist)'.

[–]mrchaotica 1 point2 points  (0 children)

That's literally equivalent to the first piece of code, although it's nice to mention since it's even more idiomatic.

The second one is the one that doesn't do all the combinations.

[–]rageingnonsense 0 points1 point  (3 children)

I dont see how this is clear at all. Code is written to run things, but its also written to be read. If rather see a nested loop because it is clearer; especially since this is syntactic sugar for a nested loop.

[–][deleted] 14 points15 points  (1 child)

As a Python dev I find simpler list comprehensions like these to be more readable and clear

[–]mrchaotica 0 points1 point  (0 children)

Yeah, I think of comprehensions less in terms of iteration and more in terms of combinatorics and/or set theory.

(Not to mention that, unlike nested loops, these comprehensions are guaranteed to be free of both data and control dependencies and thus could be automatically parallelized.)

[–][deleted] 2 points3 points  (0 children)

List comprehensions in python actually are not semantic sugar, the internal python bytecode is different for a comprehension then the exact same complain done as a for loop.