首页 > 解决方案 > Why is the time complexity of getting the length of a python list constant?

问题描述

This Python wiki says the time complexity of getting the length of a list is constant, or O(1):

lst = [4, 5, 6, 7]
len(lst)
# 4

However, I would expect it to be linear, or O(n), because all of the items in the list need to be counted. Is the length cached by the list? If not, how is the time complexity constant?

标签: pythonarraystime-complexity

解决方案


推荐阅读