In my head I read the first line as "budget dot dict for budget in budgets" and immediately understand what it's doing. The second one takes a little longer (honestly not more than a second but still)
So the second version wasn't really hard to read then? I mean, if you can grasp what the three lines does in less then a second you can't really call that hard.
As I said, I don't use Python, but the first version gave me a slight feeling of discomfort. I don't really like seeing something being used before it's defined. It would make more sense to me if it was the other way around.
Your point about 'seeing things being used before they're defined' kinda did obfuscate that argument.
Anyway, I'd argue that the list comprehension is still more readable than the for loop method.
The list comprehension simply defines 'this list contains all of the budgets as dictionaries', initializing the list with its contents in it, ready to use instantly.
The for loop approach, whilst still very much readable, still has the extra boilerplate of the for loop structure, and I'd argue that the unnecessary 'defining the contents of the list afterwards instead of initializing the list pre-filled' could arguably hurt readability in the long run, because of the additional verbosity being used in the completion of the simple task potentially obfuscating the intended contents of that list to a greater extent than would have happened if a list comprehension was used instead (and requiring anyone looking at that function later on to need to read three separate statements to see how the contents of the list are being set up instead of only needing to read the one statement)
It's not harder but it's slower to read. "This is a list where each element is a dict conversion of that other list" vs "make an empty list, loop through that other list, append the dict version of the element to that first list"
It also makes you think in different terms, the former is declarative, the latter is procedural.
It’s not so much that it’s harder to read, it’s that it is less efficient code. Python’s list comprehension is a major pro and it’s not all that complicated to understand. Like the top comment says, this is just dumbing the code down for people who stand in the way of progress and learning new things.
Fair point, good sir. I’m with you that the less pythonic way is not any more difficult to read. For most, it’s probably easier to read unless they’re familiar with list comprehension already.
View all comments
127
u/Putalittlefence Apr 30 '22
I get clearing up code where someone's been a bit comprehension-happy but jeez this makes it so much harder to read