Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension for loops Python

I use a lot of N dimensional arrays and it gets a pain to have to write such indented code and I know some codes can be replaced with list comprehensions and inline statements. For example:

for x in (0,1,2,3):     for y in (0,1,2,3):         if x < y:             print (x, y, x*y) 

can be replaced with:

print [(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y] 

But how could I change the action instead of print to do something else like:

total = x+y 

So what I want to do is something like:

[(total+=x+y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y] 

However this doesn't work

Is there a smart way to do this rather than:

for x in (0,1,2,3):         for y in (0,1,2,3):             if x < y:                 total+=x+y 
like image 682
disruptive Avatar asked Oct 21 '11 09:10

disruptive


People also ask

Is a list comprehension a for loop?

List comprehensions are also more declarative than loops, which means they're easier to read and understand. Loops require you to focus on how the list is created. You have to manually create an empty list, loop over the elements, and add each of them to the end of the list.

Can you use while loops in list comprehension Python?

No, you cannot use while in a list comprehension. There is not a single while statement allowed anywhere. The only keywords you are allowed to use is a for , for a for loop.

Is list comprehension better than for loop Python?

Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.

What is the difference between list comprehension and for loop?

List comprehensions are the right tool to create lists — it is nevertheless better to use list(range()). For loops are the right tool to perform computations or run functions. In any case, avoid using for loops and list comprehensions altogether: use array computations instead.


2 Answers

sum works here:

total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y) 
like image 192
Jochen Ritzel Avatar answered Oct 11 '22 22:10

Jochen Ritzel


As an alternative to writing loops N levels deep, you could use itertools.product():

In [1]: import itertools as it  In [2]: for x, y in it.product((0,1,2,3),(0,1,2,3)):    ...:     if x < y:    ...:         print x, y, x*y  0 1 0 0 2 0 0 3 0 1 2 2 1 3 3 2 3 6 

This extends naturally to N dimensions.

like image 23
NPE Avatar answered Oct 11 '22 22:10

NPE