Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does shorthand if assignment to list not work?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading