简体   繁体   中英

What is the complexity of index for lists of lists(e.g. list[x][y])

In python

lst = [[1,2,3...],[4,5,6...]]

Assume I have a list whose length is n 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?

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

Indexing is an O(1) operation (constant time). Thus, two successive indexing operations is still O(1) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM