Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which gives better performance: len(a[:-1]) or len(a)-1

In Python which is better in terms of performance:

1)

for i in range(len(a[:-1])):
    foo()

or

2)

for i in range(len(a)-1):
    foo()

UPDATE:

Some context on why I'm looping over indices (non-idiomatic?):

for c in reversed(range(len(self._N)-1)):
    D[c] =  np.dot(self._W[c], D[c-1])*A[c]*(1-A[c])
like image 663
blaze Avatar asked Jan 24 '26 02:01

blaze


1 Answers

The second one is better, two reasons:

  1. The first one created a new list a[:-1], which takes up unnecessary time & memory, the second one didn't create a new list.

  2. The second one is more intuitive and clear.

[:] returns a shallow copy of a list. it means that every slice notation returns a list which have new address in memory, but its elements would have same addresses that elements of source list have.

like image 193
Dinever Avatar answered Jan 25 '26 15:01

Dinever