0
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ This question lacks context. See How to Ask. What are the inputs and outputs? What is the 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\$ Commented Jul 26, 2017 at 20:29
  • 1
    \$\begingroup\$ @200_success I don't really think that matters in this case since I was asking how to loop over a list and replace values in a Pythonic way (this pattern often comes back in my code). If that makes it off-topic, I'll add some context tomorrow. It would be a shame to delete this question since alecxe wrote such a good answer. Should this be moved to Stack Overflow? \$\endgroup\$ Commented Jul 26, 2017 at 20:36

1 Answer 1

3
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\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\$ Commented Jul 26, 2017 at 20:20
  • \$\begingroup\$ @redfast00 gotcha, added a note about the if/else shorthand expression for completeness sake. Thanks. \$\endgroup\$ Commented Jul 26, 2017 at 20:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.