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)

Answer from avarice on Stack Overflow
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity - Python Wiki
This page documents the time-complexity (aka "Big O" or "Big Oh") of various operations in current CPython. Other Python implementations (or older or still-under development versions of CPython) may have slightly different performance characteristics.
Discussions

What is the runtime complexity of Python's deepcopy()? - Stack Overflow
That's the complexity part, but the constant is large and deepcopy is anything but cheap and could very well be causing your problems. The only sure way to know is to use a profiler -- do it. FWIW, I'm currently rewriting terribly slow code that spends 98% of its execution time in deepcopy. ... Sign up to request clarification or add additional context in comments. ... What are you using deepcopy for? As the name suggests, deepcopy copies ... More on stackoverflow.com
🌐 stackoverflow.com
How to copy python list in constant time?
It's only included in python premium's version, for 20$/month More on reddit.com
🌐 r/leetcode
22
0
December 7, 2024
arrays - Does creating a deep copy of a string of size N (in python) take space complexity O(N) or O(1)? - Computer Science Stack Exchange
My question comes from solving this LeetCode question, in which we are given a string of characters with size N, and one of the solutions is to use a hashmap (dictionary in Python) to count the More on cs.stackexchange.com
🌐 cs.stackexchange.com
February 27, 2022
What is the time complexity of slicing a list?
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. More on reddit.com
🌐 r/learnpython
13
7
January 4, 2021
🌐
Finxter
blog.finxter.com › python-list-copy
Python List copy() – Be on the Right Side of Change
The time complexity of shallow list copying—examples are list.copy() or slicing list[:]—is linear to the number of elements in the list. For n list elements, the time complexity is O(n). Why? Because Python goes over all elements in the list and adds a copy of the object reference to the ...
Top answer
1 of 4
6

Looking at the code (you can too), it goes through every object in the tree of referenced objects (e.g. dict's keys and values, object member variables, ...) and does two things for them:

  1. see if it's already been copied, by looking it in id-indexed memo dict
  2. copy of the object if not

The second one is O(1) for simple objects. For composite objects, the same routine handles them, so over all n objects in the tree, that's O(n). The first part, looking an object up in a dict, is O(1) on average, but O(n) amortized worst case.

So at best, on average, deepcopy is linear. The keys used in memo are id() values, i.e. memory locations, so they are not randomly distributed over the key space (the "average" part above) and it may behave worse, up to the O(n^2) worst case. I did observe some performance degradations in real use, but for the most part, it behaved as linear.

That's the complexity part, but the constant is large and deepcopy is anything but cheap and could very well be causing your problems. The only sure way to know is to use a profiler -- do it. FWIW, I'm currently rewriting terribly slow code that spends 98% of its execution time in deepcopy.

2 of 4
1

What are you using deepcopy for? As the name suggests, deepcopy copies the object, and all subobjects recursively, so it is going to take an amount of time proportional to the size of the object you are copying. (with a bit of overhead to deal with circular references)

There isn't really any way to speed it up, if you are going to copy everything, you need to copy everything.

One question to ask, is do you need to copy everything, or can you just copy part of the structure.

🌐
Medium
medium.com › @aiii › python-copy-shallow-and-deep-ce1959e26a3b
Python Copy: Shallow and Deep
September 23, 2020 - 3. Deep copy is an `O(NM)` complexity algorithm where `N` is the length of the original compound object, and `M` is the average length (in terms of non-compound objects) of the elements in the compound. 4. The shallow and deep copy for non-compound objects are the same, for example, `int`, `float`, `str` etc. 5. `list.copy` is the same as using slice, i.e. `a[:]` Python ·
Find elsewhere
🌐
Finxter
blog.finxter.com › home › learn python blog › python set copy()
Python Set copy() - Be on the Right Side of Change
April 17, 2021 - The runtime complexity of the set.copy() function on a set with n elements is O(n) because Python creates a new empty set and adds one element at a time to the set. This procedure is repeated n times.
🌐
Reddit
reddit.com › r/learnprogramming › create and copy a linked list complexity.
r/learnprogramming on Reddit: Create and copy a linked list complexity.
October 3, 2022 -

I have created a copy-method in the code. It creates and returns a copy of the LinkedList object. However, I have been asked to create a more efficient method. I have three questions:

1 - What is the complexity of my copy method? Do I have to take into account the complexity of the insert-method when calculating the complexity? 2 - How would you rewrite the code so it gets a better complexity! And which would be this complexity?

Code:

class LinkedList:

class Node:
    def __init__(self, data, succ):
        self.data = data
        self.succ = succ

def __init__(self):
    self.first = None

def insert(self, x):
    if self.first is None or x <= self.first.data:
        self.first = self.Node(x, self.first)
    else:
        f = self.first
        while f.succ and x > f.succ.data:
            f = f.succ
        f.succ = self.Node(x, f.succ)
def copy(self):               
    result = LinkedList()
    for x in self:
        result.insert(x)
    return result
🌐
UCI
ics.uci.edu › ~pattis › ICS-33 › lectures › complexitypython.txt
Complexity of Python Operations
In fact, we could also simplify copy = list(alist) O(N) copy.sort() O(N Log N) - for fast Python sorting to just copy = sorted(alist) O(N Log N) - for fast Python sorting because sorted will create a list of all the values in its iterable argument, and return it after mutating (sorting) it.
🌐
DEV Community
dev.to › iihsan › time-complexity-analysis-of-python-methods-bigo-notations-for-list-tuple-set-and-dictionary-methods-47l9
Time Complexity Analysis of Python Methods: Big(O) Notations for List, Tuple, Set, and Dictionary Methods - DEV Community
January 15, 2024 - For example, list.append(). As the list reserves some memory, so until it is utilized, list.append() gives O(1). However, when the reserved memory is filled, and new memory is required, a new list is created with more space, copying all elements. While this operation is not always constant time, it happens infrequently. So, we refer to it as Amortized constant time. The IN Operator uses linear search with a time complexity of O(n). Thanks for reading! Feel free to like, comment, and share if you find this article valuable. You can check my other articles as well: Mastering Metaclasses in Python using real-life scenarios Use Asynchronous Programming in Python: Don’t Block Entire Thread
🌐
Stack Overflow
stackoverflow.com › questions › 65941554 › timing-complexity-for-copy-in-python-how-do-i-add-the-elapsed-time
Timing complexity for copy() in python. How do I add the elapsed time? - Stack Overflow
January 28, 2021 - import timeit def copytest(n): ... = endtime - starttime elapsedtime += elapsedtime return elapsedtime for j in range(1, 100): print(j, copytest(j)) This code is able to recognise the complexity of copy comma...
🌐
GeeksforGeeks
geeksforgeeks.org › set-copy-python
set copy() in python - GeeksforGeeks
February 14, 2023 - # Python3 program to demonstrate the use # of join() function set1 = {1, 2, 3, 4} # function to copy the set set2 = set1.copy() # prints the copied set print(set2) Output: {1, 2, 3, 4} Time complexity : O(1), space complexity: O(n) Shallow Copy Example : Python ·
🌐
GitHub
gist.github.com › 4586896
Time complexity document from the python wiki is gone. I got the last cached copy from Internet Archive and recreated it here. Thanks Internet archive! Original source: http://wiki.python.org/moin/TimeComplexity Last copy from Internet archive: http://web.archive.org/web/20121023182950/http://wiki.python.org/moin/TimeComplexity · GitHub
Original source: http://wiki.python.org/moin/TimeComplexity Last copy from Internet archive: http://web.archive.org/web/20121023182950/http://wiki.python.org/moin/TimeComplexity ... This page documents the time-complexity (aka "Big O" or "Big Oh") of various operations in current CPython.
🌐
GeeksforGeeks
geeksforgeeks.org › complexity-cheat-sheet-for-python-operations
Complexity Cheat Sheet for Python Operations - GeeksforGeeks
December 13, 2024 - This cheat sheet is designed to help developers understand the average and worst-case complexities of common operations for these data structures that help them write optimized and efficient code in Python. Python's list is an ordered, mutable sequence, often implemented as a dynamic array. Below are the time complexities for common list operations:
🌐
DEV Community
dev.to › global_codess › time-complexities-of-python-data-structures-3bja
Time Complexities Of Python Data Structures - DEV Community
February 19, 2020 - Some of the key and general operations include iterating over a collection, inserting an item at a point in the collection, deleting, updating or creating a copy of an item or the entire collection. In programming, the choice of the data structure is very important as it affects the performance of the application. This is because the operations of the data structures have different time and space complexities.
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › pythons-list-append-method-has-01-time-complexity
Why Python’s list.append() Method Has O(1) Time Complexity
Appending to a list is considered amortized O(1) time complexity. Here’s why: When the array runs out of space, Python allocates a larger block of memory (usually more than double the current size) and copies all elements to the new space. This copy operation is costly, but it doesn’t happen with every append.
🌐
Stack Overflow
stackoverflow.com › questions › 45672593 › what-is-the-time-complexity-of-dictionary-on-all-operation-with-tuple-value-as-i
What is the time complexity of dictionary on all operation with tuple value as its key in python? - Stack Overflow
For copy or iteration, it's logical that it is O(n) as there is n elements that you can access in O(1) complexity. As commented by Laurent, all dictionnary are "stored" based on the hash of the key (link).
🌐
Bradfield CS
bradfieldcs.com › algos › analysis › performance-of-python-types
Performance of Python Types
Python is still an evolving language, which means that the above tables could be subject to change. The latest information on the performance of Python data types can be found on the Python website. As of this writing, the Python wiki has a nice time complexity page that can be found at the ...