\$\begingroup\$
\$\endgroup\$
2
I often write code like this:
newarguments = []
for argument in arguments:
if parser.is_label(argument):
argument = str(labels[argument])
newarguments.append(argument)
but this feels really unpythonic. Is there a better way to loop over a list and replace certain values?
asked Jul 26, 2017 at 19:53
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
A common way to collapse a list "mapping" code block like this is to use a list comprehension combined with a ternary conditional operator:
newarguments = [str(labels[argument]) if parser.is_label(argument) else argument
for argument in arguments]
List comprehensions are also generally faster (reference).
answered Jul 26, 2017 at 20:06
-
\$\begingroup\$ I considered list comprehension before asking this question, but didn't know about the 'else', leading to a bug that removed all non-labels. The docs you linked also don't mention that an else can be used in a list comprehension. I love to learn these 'hidden' features in Python! \$\endgroup\$redfast00– redfast002017年07月26日 20:20:43 +00:00Commented Jul 26, 2017 at 20:20
-
\$\begingroup\$ @redfast00 gotcha, added a note about the if/else shorthand expression for completeness sake. Thanks. \$\endgroup\$alecxe– alecxe2017年07月26日 20:23:16 +00:00Commented Jul 26, 2017 at 20:23
lang-py
parser
? Please be specific. If, by "I often write code like this", you are asking for advice about unspecified hypothetical code, then this question is off-topic for Code Review. \$\endgroup\$