Question

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']
Was it helpful?

Solution

.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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top