What is the complexity of using list() while copying a list in python?

Viewed 2004

I have a list:

a = [1,2,3,4]

and now I want to make a copy of the list a as list b

b = list(a)

I want to know the complexity of the step where I make a copy of the list a.

3 Answers

When a list is copied:

  • list.copy()
  • list[:]
  • list()

It iterates thorugh all elements. So the time complexity defined by thr size of the list i.e. O(n)

When you do a copy operation on mutable datatypes:

b = list(a)
a is b # False

It copies the whole data to another memory location and the time complexity is defined by the total size of the list i.e. O(n)

If you had assigned it like following (Aliasing):

b = a
a is b # True

Then the time complexity would be O(1)

For more detail look here

Shallow Copying, Slicing takes O(n) Because Python goes over all elements in the list and adds a copy of the object reference to the new list (copy by reference).

Shallow Copying

list.copy()

List Slicing

list[:]

use the built-in list constructor list(...)

list()

Use list comprehension

[e for e in lst]

Related