Some say "if you care about speed you shouldn't use Python". Others say "since Python isn't fast, you have to optimize it to make it viable".
The behavior of len() depends on the class definition.
Calling len() is always taking constant time for iterable data structures(string, list, tuple, etc.). That's because they have __len__() defined that way. They use a counter which is altered when the iterable in question is altered. len() is therefore just returning a counter in this scenario.
Without defining __len__() you can't use len() on it. Since it's up to the creator of the class to define what this dunder method should do and return, you can have any time complexion. You could for example traverse something every time the method is called.
Inga kommentarer:
Skicka en kommentar