In Python, what is the time complexity when we create a sublist from an existing list?
For example, here data is the name of our existing list and list1 is our sublist created by slicing data.
data = [1,2,3,4,5,6..100,...1000....,10^6]
list1 = data[101:10^6]
What is the running time for creating list1?
Is it O(10^6) i.e.O(N), or O(1)?
Python operator module has in-built length_hint() function to calculate the total number of elements in the list. The operator. length_hint() method is used to find the length of an iterable such as list, tuple, dict, etc.
O(n) where n is the length of the slice. Slicing is just "copy part of the list" so time complexity is the same as copy.
The average time complexity of the in operator for lists is O(n) . It becomes slower when there are many elements. The execution time varies greatly depending on the position of the value to look for. It takes the longest time when its value is at the end or does not exist.
Slicing is just “copy part of the list” so time complexity is the same as copy. O(n+k) is the average case, which includes having to grow or shrink the list to adjust for the number of elements inserted to replace the original slice.
Getting a list slice in python is O(M - N)
/ O(10^6 - 101)
Here you can check python list operations time complexity
By underneath, python lists are represented like arrays. So, you can iterate starting on some index(N) and stopping in another one(M)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With