I’m new to python and came across this segment of code. Can someone help me with the syntax here? Maybe provide some comments on each line to how it’s working? xs is a list that contains dates.
data = {}
for title, d in tmpdata.items():
data[title] = [x in d and d[x][statid] or 0 for x in xs]
data[title][-1] = maxs[statid]
If I had to guess, I’d say the most perplexing line to someone new to Python must be:
There is a lot going on here, and some of it uses a style that, although safe in this instance, is no longer recommended. Here is a more verbose form:
The construct
condition and value-if-condition-is-true or value-if-condition-is-falseis an old-style form of the C ternary formcondition ? value-if-condition-is-true : value-if-condition-is-false. The given Python expression hides a latent bug that can crop up if thevalue-if-condition-is-trueis evaluated by Python as a “false-y” value –0, [], ()are all values that would be considered as false if used in a conditional expression, so you might have a problem if yourvalue-if-condition-is-trueturned out to be one of these. As it happens in this case, ifd[x][statid]is 0, then we would assume a False result and go on and add a 0 to the list, which would be the right thing to do anyway. If we could just edit the verbose form, the simplest would be to remove theand d[x][statid]as in:Or use the new Python ternary form (which gives some people a rash, but I have grown accustomed to it – the ternary form, not the rash), which is written as:
Or substituting into our verbose form:
So lastly, the list comprehension part. Whenever you have this kind of loop:
You can rewrite it as:
and this form is called a list comprehension. It creates a list by following the iteration condition and evaluating the value for each iteration.
So you can now see how the original statement would be written. Because of the possible latent bug inherent in the old-style
condition and true-value or false-value, the ternary form or an explicit if-then-else is the preferred style now. The code should be written today as: