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

Ternary operator with lists

I have a list of strings in Python, in which some of the strings start with character -, and I want to remove such character.

I tried this sentence:

columns = [column[1:] for column in columns if column.startswith('-') else column]

but I get a Sintax Error exception.

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

What is the right way to do this?

>Solution :

You want the result of the ternary operator to be the thing that goes in the list, so it all goes on the left:

columns = [column[1:] if column.startswith('-') else column for column in columns]

You can use an if after the for .. in ... to filter items out of the iteration completely, but else has no meaning in that context, which is why you got a SyntaxError.

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