Reputation: 31
In python
lst = [[1,2,3...],[4,5,6...]]
Assume I have a list whose length isn
and each nested list has the same length.
So I want to use lst[x][y]
to find some element.
what is the complexity of it?
I tried to google it but not find answers.
Edited:Thanks guys! So if I input a list containing n lists (each containing n elements), then how many times do I index the list (in terms of n)? Is it 2n?
Upvotes: 3
Views: 584
Reputation: 83527
This page shows that "get item" is O(1)
. To analyze an expression like l[x][y]
it might be helpful to break it into its components:
temp = l[x]
temp[y]
When analyzing sequential operations, we add the time complexity. So this is O(1) + O(1)
. But this simplifies to just O(1)
.
Upvotes: 2
Reputation: 362746
Time complexity of Python data structures are documented here:
https://wiki.python.org/moin/TimeComplexity
The one you're asking about is "Get Item" for list
, and it's O(1). Even though you index a list and a nested list, that's still O(1).
Upvotes: 3
Reputation: 77847
Indexing is an O(1) operation (constant time). Thus, two successive indexing operations is still O(1).
Upvotes: 2