I tested two different ways to reverse a list in python.
import timeit
value = [i for i in range(100)]
def rev1():
v = []
for i in value:
v.append(i)
v.reverse()
def rev2():
v = []
for i in value:
v.insert(0, i)
print timeit.timeit(rev1)
print timeit.timeit(rev2)
Interestingly, the 2nd method that inserts the value to the first element is pretty much slower than the first one.
20.4851300716
73.5116429329
Why is this? In terms of operation, inserting an element to the head doesn't seem that expensive.
Python lists are resizeable therefore appending is very fast. If you intend to append few values (compared to the amount already there) and don't need a new array, then yes, numpy.append should be slower than list 's .append for a large enough array (for N elements in one array and M in the other it'd be O (N + M) compared to amortized O (M)).
Not having to declare the type isn’t what makes Python slow, the design of the Python language enables you to make almost anything dynamic. You can replace the methods on objects at runtime, you can monkey-patch low-level system calls to a value declared at runtime.
In this article, we are going to discuss the difference between append (), insert (), and, extend () method in Python lists. It adds an element at the end of the list. The argument passed in the append function is added as a single element at end of the list and the length of the list is increased by 1.
numpy.append () in Python --- faster than appending to a List ? Python numpy append () function is used to merge two arrays. This function returns a new array and the original array remains unchanged. ---------- So it sounds like List.append (new_value) is faster. That's right.
insert
is an O(n)
operation as it requires all elements at or after the insert position to be shifted up by one. append
, on the other hand, is generally O(1)
(and O(n)
in the worst case, when more space must be allocated). This explains the substantial time difference.
The time complexities of these methods are thoroughly documented here.
I quote:
Internally, a list is represented as an array; the largest costs come from growing beyond the current allocation size (because everything must move), or from inserting or deleting somewhere near the beginning (because everything after that must move).
Now, going back to your code, we can see that rev1()
is an O(n)
implementation whereas rev2()
is in fact O(n2)
, so it makes sense that rev2()
will be much slower.
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