1

I'm curious about how to make code more efficient in Python, I've got to execute an action, which may or may not have a payload attached depending on the length of a list.

Right now, I'm using an if statement to determine if there is a payload. Is there a better or cleaner way to find this?

                    #If payload, execute action with it
                    if(len(data) > 1):
                        action= mec.action(data[1])
                    #If no payload, then just execute action
                    else:
                        action= mec.action()
                    return action
3
  • 1
    What type of efficiency are you looking for? Commented Aug 14, 2016 at 1:44
  • ideally cleaner code / better logic. I don't think it's possible to make this more efficient in terms of time? Commented Aug 14, 2016 at 1:47
  • It looks fine as it is: if you remove the comments, the code is still understandable. The only things I'd change is the if statement: you don't need those parentheses. Commented Aug 14, 2016 at 1:49

3 Answers 3

3

The code is efficient as is - instead of optimising for efficiency, try optimising for clarity first. If the code then becomes a performance hotspot... think about looking at the efficiency.


Remembering that a return ends a function; this is a slightly cleaner alternative:

# execute with payload if exists
if(len(data) > 1):
    return mec.action(data[1])
# execute without payload 
# this isn't reached if len(data) > 1
return mec.action()
Sign up to request clarification or add additional context in comments.

1 Comment

"try optimising for clarity first." This is something that can take a long time to learn in software. Clever code is the bane of maintainers, including yourself 6 months from now. Write clean code, profile the performance, then optimize what needs to be optimized ... and comment the crap out of anything even vaguely "clever."
2

Python comes with vararg syntax you can use for this directly.

return mec.action(*data[1:])

(I'm assuming here that data[2] onwards aren't meaningful, or you could use mec.action(*data[1:2]))

Comments

0

In this case just use a ternary operator like this:

return mec.action(data[1]) if(len(data) > 1) else mec.action() 

Hope it helps!

Comments

Your Answer

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.