I have gone through many blogs regarding python time complexity and posting my doubt:
In case of list comprehensions how will the time complexity be analysed?
For example:
x = [(i,xyz_list.count(i)) for i in xyz_set]
where xyz_list = [1,1,1,1,3,3,4,5,3,2,2,4,5,3]
and xyz_set = set([1, 2, 3, 4, 5])
So, is the complexity the one line of code O(n*n*n)
[i.e., O(n)
for iteration, O(n)
for list creation, O(n)
for count function]??
“List comprehension” is not the kind of thing that has “time complexity”. An algorithm which processes an input of size in a particular way can be examined for its running time as a function of . “List comprehension” is a nice syntax for specifying lists. It is not an algorithm.
If iterations are performed over computationally expensive function, list and for-loop runtime may be almost the same. where a list comprehension and for-loop run time is compared for a simple function of multiples of 2 in each loop. The results showed that list comprehension was twice faster than for-loop.
List Comprehensions help us in reducing the execution time of a program where you are required to create a list based on any mathematical expression. We will consider an example to prove the above statement.
As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds). List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
This is quadratic O(n^2)
:
x = [(i,xyz_list.count(i)) for i in xyz_set]
xyz_list.count(i)) # 0(n) operation
for every i
in xyz_set
you do a 0(n)
xyz_list.count(i)
You can write it using a double for loop which will make it more obvious:
res = []
for i in xyz_set: # 0(n)
count = 0
for j in xyz_list: # 0(n)
if i == j: # constant operation 0(1)
count += 1 # constant operation 0(1)
res.append(count) # constant operation 0(1)
Python time complexity
usually when you see a double for loop the complexity will be quadratic unless you are dealing with some constant number, for instance we just want to check the first 7 elements of xyz_list
then the running time would be 0(n)
presuming we are doing the same constant work inside the inner for:
sec = 7
res = []
for i in xyz_set:
count = 0
for j in xyz_list[:sec]:
......
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