Home > Blockchain >  How come changing "if else" code into a one-liner breaks it?
How come changing "if else" code into a one-liner breaks it?

Time:12-11

For this statement here, it works perfectly with the long version, but for the one-liner, it says "TypeError: unsupported operand type(s) for =: 'int' and 'NoneType'". I kept the commands in the if statement the exact same and it doesn't seem like the syntax is the issue (since it's type error). The all_lines is just provided as an example, though I've tried with other types of lists and they don't work with the one-liner either

Doesn't work:

all_lines = [["han"], ["and"], ['']]
for i, line in enumerate(all_lines):
    j  = 1 if line == [''] else monkeys[j].append(line)

Works:

all_lines = [["han"], ["and"], ['']]
for i, line in enumerate(all_lines):
    if line == ['']:
        j  = 1
    else:
        monkeys[j].append(line)

CodePudding user response:

Because the ternary conditional applies to the expression after =, not to the entire line. In other words, your attempt translates to

# BUG: adding the wrong thing
for i, line in enumerate(all_lines):
    if line == ['']:
        what = 1
    else:
        what = monkeys[j].append(line)
    j  = what

If you really insist on using a ternary conditional, perhaps try something like

for line in all_lines:
    j  = 1 if line == "" else monkeys[j].append(line) or 0

though the longhand certainly seems preferable for legibility as well as pythonicity.

In your example data, the elements of all_lines are lists, not strings, so the condition will never be true. Did you perhaps mean to check for equivalence to the list [''], or to loop over the individual list subelements; or for the list to contain strings?

CodePudding user response:

What your short version is actually doing is the following:

all_lines = [["han"], ["and"], ['']]
for i, line in enumerate(all_lines):
    if line == ['']:
        j  = 1
    else:
        j  = monkeys[j].append(line)

so in the else part you are trying to add the return value of List.append() which is None, hence you get a TypeError. From the snippet you provided it is a bit difficult to see what you are trying to achieve. It seems you are not using the counter of enumerate (i) so you may as well remove enumerate.

  • Related