How can I calculate the time complexity of zip()?
testList = [[1,2,3]for _ in range(5)]
zip(*testList)
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.
Time complexity: O(N+K) Space Complexity: O(K) Worst case: when data is skewed and range is large.
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.
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.
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.
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