Hello @eby.annie, @scarlett.patrick22,
I will try my best to clarify as I was in the same boat as you.
This is how I see it:
# Let's say..
N = 10
M = 20
list4 = [[i + j for j in range(M)] for i in range(N)] # N*M
list5 = [min(list4[i]) for i in range(N)]
This is what list4
holds:
for i, v in enumerate(list4):
print(f"{i}: {v}")
Output:
0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
2: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
3: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
4: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
5: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
6: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
7: [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
8: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]
9: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
As you see, the length of each entry in list4
is not the same as N
.
The maximum length we see is at list4[9]
. It is of length 20, which is the value of M
.
Let’s see this for the worst-case scenario because the O
rder of Time complexity is measured against the worst case:
Even though accessing a list by its index is a constant time operation O(1)
,
list5 = [min(list4[i]) for i in range(N)]
translates to:
list5 = [min(list4[9]) for 9 in range(0..9)]
when i = 9
, which again translates to:
list5 = [min([9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28])]
Now, what is the cost of performing min(list4[9])
whose size is M
?
The whole list of size M
is scanned to find the minimum.
This is the cost of the hidden operation.
So for every N
, the hidden cost is M
, which is of the O
rder(N*M)
Hope this clears it up!
Do let me know.