Why does shorthand if assignment to list not work?

Question:

Trying to use the code given below I get the error: row[0] = "M" if row[0] == "male" else row[0] = "F" ^^^^^^ SyntaxError: cannot assign to subscript here. Maybe you meant '==' instead of '='?

rows = []
    for row in csvreader:
        row[0] = "M" if row[0] == "male" else row[0] = "F"
        rows.append(row)

However when I format it normally(see below) the error does not occur. Why is that?

    for row in csvreader:
        if row[0] == "male":
            row[0] = "M"
        else:
            row[0] = "F"
        rows.append(row)

Note: row is list of strings

Looking online at the error given it says it occurs because of an assignment to a literal, which doesn’t seem to be the case.

Asked By: Rando Coder

||

Answers:

This is how to write the ternary expression

for row in csvreader:
    row[0] = "M" if row[0] == "male" else "F"
    rows.append(row)

The other method, less pythonic, is to use an if statement, and two assignments

for row in csvreader:
    if row[0] == "male":
        row[0] = "M"  
    else:
        row[0] = "F"
    rows.append(row)
Answered By: Eureka
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.