Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity for a sublist in Python

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)?
like image 957
Sriram Avatar asked Sep 05 '16 22:09

Sriram


People also ask

How do you find the length of a sub list in Python?

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.

What is the time complexity of list slicing Python?

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.

What is the time complexity of list in python?

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.

What is the runtime of list slicing?

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.


1 Answers

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)

like image 173
levi Avatar answered Sep 18 '22 11:09

levi