Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of zip() in Python?

How can I calculate the time complexity of zip()?

testList = [[1,2,3]for _ in range(5)]
zip(*testList)
like image 779
Dean Wong Avatar asked Apr 26 '16 23:04

Dean Wong


People also ask

What is zip () in Python?

Python zip() Function The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

What is the time and space complexity of sort () in Python?

Time complexity: O(N+K) Space Complexity: O(K) Worst case: when data is skewed and range is large.

What is time complexity in Python?

Time complexity is a measure that determines the performance of the code which thereby signifies the efficiency of the same. It is always a good practice to think about the performance while writing the code. Note: The lesser the time complexity of the code means the faster execution of it.

What is time complexity of in function in Python?

The average time complexity of the in operator for sets is O(1) . It does not depend on the number of elements. The execution time does not change depending on the value to look for. If you want to repeat in operation for a list with many elements, it is faster to convert it to a set in advance.


1 Answers

Assume you zip N iterables.

In python 3.x, the zip function itself runs in O(1) time, as it just allocates a special iterable (called the zip object), and assigns the parameter array to an internal field. The function invocation itself (before control reaches in zip) is O(N), as the interpreter must convert the parameters to an array. Every subsequent next call on the iterator also runs in O(N). Exhausting the zip object is therefore O(N*M) assuming M is the average (or minimum) length of the iterables, excluding the time the iterables themselves take to generate items (as it is independent of zip).

In python 2.x, the zip function returns a list. That list must be constructed during the call, that is equvivalent to exhausting the iterator in the previous example, so O(N*M), not counting the time spent in the zipped iterables.

like image 65
Tamas Hegedus Avatar answered Sep 18 '22 17:09

Tamas Hegedus