Is there a convention of when and how to store values of len()
or sum()
in python? To provide an example, if you have a Class
class MyClass:
def __init__(self, single_number = 4, multiple_numbers = [1,2,3]):
self.single= single_number
self.multiple = multiple_numbers
def info(self):
print(f"The length of multiple is {len(self.multiple)}")
print(f"The length of multiple is {len(self.multiple)*4}")
print(f"The length of multiple is longer than {len(self.multiple)-1}")
if __name__ == "__main__":
test=MyClass()
test.info()
# other stuff
test.info()
At what point would you start storing len(self.multiple)
as its own value? Thankfully, python spares the use of len
for some tasks like for my_numbers in multiple_numbers:
so I wouldn't need it just for iterations. In addition, the value of len
is static for the instance of the class and will be needed (probably) multiple times at different parts within the runtime, so it is not a temporary variable like here. In general, this seems to be a tradeoff between (very small amounts) of memory vs computation. The same issue applies to sum()
.
Parts of these questions are opinion-based, and I am happy to hear what you think about it, but I am looking primarily for a convention on this.
- At what point, if any, should
len(self.multiple)
be stored as its own value? - Is there a convention for the name?
length_of_multiple_numbers
seems bloated but would be descriptive.