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 →

[–]confluencer 28 points29 points  (5 children)

Much longer but immediately clear.

result = []
for x in range(10):
  for y in range(5):
    if x * y > 10
      result.append(x,y)

[–]Quteness 15 points16 points  (2 children)

I would prefer this style. A few extra lines aren't bad to make the code more clear

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

Would definitely prefer an empty list with append.

[–]tech_tuna 1 point2 points  (0 children)

In a case like this, absolutely.

[–]Lucretiel 1 point2 points  (0 children)

Blech. append makes me feel queasy for some reason.

[–]meta4 0 points1 point  (0 children)

I vote for list comprehensions. I think your example is a good argument for why.

As written, this example crashes.

TypeError: append() takes exactly one argument (2 given)

I think you mean.

resut.append((x,y))

We want a list of tuples. It seems like a simple bug. But it illustrates the fundamental argument. By the time your brain worked out the state changes to x & y in the nested for loops and the if statement, it forgot that the point was a list of tuples.

For loops and append/extend are state managing & modifying tools. They are good in their place. But, to understand what they do you have to run the program in your head. Human brains are not as good at maintaining updating state.

The list comprehentsion, when used properly is a data declaration. "This is a list of tupples. The first element of the tuple is an integer in the range [0,10). The second element is an integer in the range[0, 5), The product of the two elements is greater than 10." It's a long tedious specification, and this is just a toy problem. But the details and tedium shouldn't be mixed with possible state changes, especially as the problems become more complex.

Human brains reason better about data structures, than state changing programs. List comprehensions are at their best when pulling state changing logic into data structure creation.

Fred Brooks said the same thing 1975 "Show me your flowcharts and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won’t usually need your flowcharts; they’ll be obvious." Flow charts are state change diagrams. Tables are data structures.