Get item is getting an item in a specific index, while lookup means searching if some element exists in the list. To do so, unless the list is sorted, you will need to iterate all elements, and have O(n) Get Item operations, which leads to O(n) lookup.

A dictionary is maintaining a smart data structure (hash table) under the hood, so you will not need to query O(n) times to find if the element exists, but a constant number of times (average case), leading to O(1) lookup.

Answer from amit on Stack Overflow
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity - Python Wiki
[2] = Popping the intermediate ... 1 moves. The average case for an average value of k is popping the element the middle of the list, which takes O(n/2) = O(n) operations....
Discussions

What is the time complexity of the “in” operation
This moved much faster. Because it does fewer tests - if you're checking for membership in a list, you can stop as soon as you find the element. If you're comparing every element of the list to a value, as the first example does, then you check every element of the list. Doing less is always faster. More on reddit.com
🌐 r/learnpython
10
2
September 1, 2021
performance - Cost of list functions in Python - Stack Overflow
Isn't the whole point of a list ... the time complexity of insert and delete to O(1)? From the above, it seems more like the underlying data structure is an array. Am I missing something? 2013-02-28T06:59:26.257Z+00:00 ... @AKE see array list. There are tradeoffs in different implementations of data structures. In your typical O(1) insert/delete list you often have Get Item as ... More on stackoverflow.com
🌐 stackoverflow.com
Time Complexity of Python list comprehension then list[i] = value vs. list = [] then list.append(value)
In terms of Big O the algorithms are equivalent to each other as they both have linear growth. As you say, the list comprehension in the first example is O(n) so the function is O(2n), but in algorithmic analysis that is considered equivalent to O(n). In practical terms the second approach is better as it only requires one iteration over the input array. More on reddit.com
🌐 r/learnprogramming
5
2
September 26, 2021
linux - Time complexity of a huge list in python 2.7 - Stack Overflow
I've a list which has approximately 177071007 items. and i'm trying to perform the following operations a) get the first and last occurance of a unique item in the list. b) the number of occurances... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › @ivanmarkeyev › understanding-python-list-operations-a-big-o-complexity-guide-49be9c00afb4
Understanding Python List Operations: A Big O Complexity Guide | by Ivan Markeev | Medium
June 4, 2023 - Python lists are versatile data ... of items. When working with lists, it’s important to understand the efficiency of different operations. In this article, we will explore the Big O complexity of common list operations, helping you make informed decisions about algorithm design and performance optimizations. Accessing an element in a Python list by its index is an efficient operation with constant time ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › complexity-cheat-sheet-for-python-operations
Complexity Cheat Sheet for Python Operations - GeeksforGeeks
July 12, 2025 - This cheat sheet is designed to help developers understand the average and worst-case complexities of common operations for these data structures that help them write optimized and efficient code in Python. Python's list is an ordered, mutable sequence, often implemented as a dynamic array. Below are the time complexities for common list operations:
🌐
DEV Community
dev.to › iihsan › time-complexity-analysis-of-python-methods-bigo-notations-for-list-tuple-set-and-dictionary-methods-47l9
Time Complexity Analysis of Python Methods: Big(O) Notations for List, Tuple, Set, and Dictionary Methods - DEV Community
January 15, 2024 - Whether you're working on real-world software or tackling problems in interviews, it's not just about writing code; it's all about writing efficient and scalable code. So, understanding the time complexity of your code becomes essential. In this article, we'll break down the Python methods for lists, tuples, sets, and dictionaries.
🌐
Sololearn
sololearn.com › en › Discuss › 2409293 › time-complexity-of-listcount-in-python
Time complexity of list.count in Python
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
UCI
ics.uci.edu › ~pattis › ICS-33 › lectures › complexitypython.txt
The Complexity of Python Operators/Functions
In fact, we could also simplify ... O(N Log N) - for fast Python sorting to just copy = sorted(alist) O(N Log N) - for fast Python sorting because sorted will create a list of all the values in its iterable argument, and return it after mutating (sorting) it. So we don't have to explicitly create such a copy in our code. This change will speed up the code, but it won't change the complexity analysis because O(N + N Log N) = O (N Log N)....
Find elsewhere
🌐
Python Morsels
pythonmorsels.com › time-complexities
Python Big O: the time complexities of different data structures in Python - Python Morsels
April 16, 2024 - Here are the time complexities of some common list operations: I've called out append, pop, and insert above because new Python programmers are sometimes surprised by the relative speeds of those operations. Adding or removing items from the end of a list are both very fast operations regardless ...
🌐
Bradfield CS
bradfieldcs.com › algos › analysis › performance-of-python-types
Performance of Python Types
Two common operations are indexing and assigning to an index position. In Python lists, values are assigned to and retrieved from specific, known memory locations. No matter how large the list is, index lookup and assignment take a constant amount of time and are thus
🌐
Reddit
reddit.com › r/learnpython › what is the time complexity of the “in” operation
r/learnpython on Reddit: What is the time complexity of the “in” operation
September 1, 2021 -

I’m not the biggest python user. But I was looking at a friends code yesterday and they had something like:

For x in (list of 40000)

For y in (list of 2.7 million)

  If x = y 

     Append something 

This was obviously super slow so they changed it to something like:

For x in (list of 2.7 million)

If y in (list of 40000)

  Append something 

This moved much faster. I get the point of one for loop being faster than two, but what is that “in” exists function doing that makes it so much faster. I always thought that to check if something exists is O(n) which shouldn’t be faster. Also this was for ML purposes so they were likely using numpy stuff.

🌐
AlgoCademy
algocademy.com › link
Time Complexity Guidelines in Python | AlgoCademy
This approach has a time complexity of O(1), which is optimal for this problem. Here is a step-by-step breakdown of the optimized algorithm: Access the first element of the array using arr[0]. Return the accessed element. def get_first_element(arr): # Access and return the first element of the array return arr[0] The code is straightforward and leverages Python's ability to access list elements in constant time.
🌐
Medium
medium.com › @hamzaehsankhan › why-len-list-has-a-time-complexity-of-o-1-a-dive-into-cpython-cbed75c38b54
Why len(list) has a time-complexity of O(1)? — A dive into CPython | by Hamza Ehsan Khan | Medium
July 13, 2023 - This in-built function is not at the mercy of the size of the list. Whether your list contains 1 element or 1000, as per the default implementation of Python (CPython), the time-complexity is O(1).
🌐
Quora
quora.com › What-are-the-time-complexity-considerations-of-lists-in-Python
What are the time complexity considerations of lists in Python? - Quora
Answer: In a normal list on average: * Append : O(1) * Extend : O(k) - k is the length of the extension * Index : O(1) * Slice : O(k) * Sort : O(n log n) - n is the length of the list * Len : O(1) * Pop : O(1) - pop from end * Insert : O(n) - n is the length of the list * Del : O(n) - n...
🌐
Reddit
reddit.com › r/learnprogramming › time complexity of python list comprehension then list[i] = value vs. list = [] then list.append(value)
r/learnprogramming on Reddit: Time Complexity of Python list comprehension then list[i] = value vs. list = [] then list.append(value)
September 26, 2021 -

Let's say we are writing a function that we know the length of the output list == length of the input list. All we need to do is to insert some value to the output list and return it. I'd like to know if one approach's time complexity is better than another?

First approach:

def someFunc(inputArray):
    result = [1 for _ in inputArray]
    for i in range(len(inputArray)):
        someValue = 100
        result[i] = someValue

vs.

def someFunc(inputArray):
    result = []
    for i in range(len(inputArray)):
        someValue = 100
        result.append(someValue)

The first approach `result[i] = someValue` is O(1) operation, however, is is list comprehension O(n) ? if that's the case then the overall algorithm would be O(2n) time?

The second approach `result.append(someValue)` can be view as O(1) ? That leads to the overall algo time complexity O(n)?

Does that mean in terms of time complexity, second approach is better than first approach? Or not?

Top answer
1 of 3
4
In terms of Big O the algorithms are equivalent to each other as they both have linear growth. As you say, the list comprehension in the first example is O(n) so the function is O(2n), but in algorithmic analysis that is considered equivalent to O(n). In practical terms the second approach is better as it only requires one iteration over the input array.
2 of 3
1
Yes, the Time Complexity of the list comprehension is O(n). You literally iterate over every list element, so if the list has n elements, then you're doing n iterations. It's going to be a little more efficient than a for a loop though. Because it's implemented in the C language and better optimized But if we are talking about Asymptotic Growth(which Big O is about). Then the Time Complexity is going to be the same for both the for loop and the list comprehension. As for the actual code you sent. In the first version, you're literally iterating over a list two times. Which kind of doesn't make sense, you could just do [100 for _ in inputArray] and omit the second loop. You can even call functions, use if-else statements from the list comprehensions, and many other things But to answer your question directly, yes it's time Complexity is n+n or O(2n). BUT 2 is constant, which isn't going to affect the Complexity Growth much. Therefore it's not considered, since it doesn't matter that much. So Asymptotic Growth is still considered O(n) With the second version, your assumption is right. Appending to the list has a time complexity of O(1). Since the list size doesn't matter for this operation. Just for your information, removing elements from the list is a very different matter. If you're removing by value or by index from the list, this operation has the worst time complexity of O(n). Because if you removed the first element for example, then under the hood, the computer has to move every single element(n-1 elements) to the left. But it's not the case with the append operation, since you simply add a new element to the end of the list and nothing else is moving. Poping the last element is also O(1) since you just remove one element from the end, and everything stays where it is
Top answer
1 of 4
1

Try the following:

from collections import defaultdict

# Keep a dictionary of our rd and pc values, with the value as a list of the line numbers each occurs on
# e.g. {'10': [1, 45, 79]}
pc_elements = defaultdict(list)
rd_elements = defaultdict(list)

with open(file, 'rb') as f:
    line_number = 0
    csvin = csv.reader(f, delimiter='\t')
    for row in csvin:
        try:
            pc_elements[int(row[0])].append(line_number)
            rd_elements[int(row[1])].append(line_number)
            line_number += 1
        except ValueError:
            print("Not a number")
            print(row)
            line_number += 1
            continue

for pc, indexes in pc_elements.iteritems():
    print("pc  {0} appears {1} times. First on row {2}, last on row {3}".format(
        pc,
        len(indexes),
        indexes[0],
        indexes[-1]
    ))

This works by creating a dictionary, when reading the TSV with the pc value as the the key and a list of occurrences as the value. By the nature of a dict the key must be unique so we avoid the set and the list values are only being used to keep the rows that key occurs on.

Example:

pc_elements = {10: [4, 10, 18, 101], 8: [3, 12, 13]}

would output:

"pc 10 appears 4 times. First on row 4, last on row 101"
"pc 8 appears 3 times. First on row 3, last on row 13"
2 of 4
0

As you scan items from your input file, put the items into a collections.defaultdict(list) where the key is the item and the value is a list of occurence indices. It will take linear time to read the file and build up this data structure and constant time to get the first and last occurrence index of an item, and constant time to get the number of occurrences of an item.

Here's how it might work

mydict = collections.defaultdict(list)
for item, index in itemfilereader: # O(n)
    mydict[item].append(index)

# first occurrence of item, O(1)
mydict[item][0]

# last occurrence of item, O(1)
mydict[item][-1]

# number of occurrences of item, O(1)
len(mydict[item])
🌐
LabEx
labex.io › tutorials › python-what-is-the-time-complexity-of-list-append-and-remove-operations-in-python-397728
What is the time complexity of list append and remove operations in Python | LabEx
We will explore the underlying mechanisms that drive the efficiency of these list operations, equipping you with the knowledge to make informed decisions when working with lists in Python. Time complexity is a fundamental concept in computer science that describes the efficiency of an algorithm or a data structure operation.
🌐
Quora
quora.com › How-do-Python-lists-maintain-constant-time-complexity-for-indexing-if-their-elements-can-be-of-more-than-one-type
How do Python lists maintain constant time complexity for indexing if their elements can be of more than one type? - Quora
Answer (1 of 4): in a C arrays where the data is held in contiguous memory, you are right that indexing couldn’t be constant time in a heterogeneous container as you would have to sum the widths of all of the previous items before being able to fetch an item (or you would need to keep a separate ...