I encounter the following small annoying dilemma over and over again in Python:
Option 1:
cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()
def do_something():
a_list = ["any", "think", "whatever"]
# read something from a_list
Option 2:
Uglier but more efficient (spare the a_list creation all over again)
a_list = ["any", "think", "whatever"]
def do_something():
# read something from a_list
What do you think?
What’s ugly about it?
Are the contents of the list always constants, as in your example? If so: recent versions of Python (since 2.4) will optimise that by evaluating the constant expression and keeping the result but only if it’s a tuple. So you could change it to being a tuple. Or you could stop worrying about small things like that.
Here’s a list of constants and a tuple of constants: