Вопрос

What does python do behind the scenes when I call:

very_big_list.index(value)

On a list of strings?

Is it more efficient than this equivalent dictionary lookup?

d = {'hello':1, 'dog':2, 'cat':3, ...}
print d['dog']
Это было полезно?

Решение

.index() loops through the list until it finds an element that is equal (element == searchterm is True). A dictionary lookup is much more efficient.

In CS terms, .index() is of O(n) complexity, dict lookups are O(1). See the Time Complexity overview on the Python Wiki.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top