Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all trailing zeroes in Python list

Tags:

python

list

Is there a faster way to remove zeros than this:

while L[-1] == 0:
    L.pop(-1)

Any prebuilt functions or anything similar?

like image 234
user230373 Avatar asked Mar 17 '23 11:03

user230373


1 Answers

Three possible micro optimizations:

1. Use del my_list[index] instead of mylist.pop(index) when you want to just delete an item by its index.

Its slightly faster:

import dis
def del_by_pop(mylist):
    mylist.pop(-1)

def del_by_del(mylist):
    del mylist[-1]

Using the dis module we can look at what's happening underneath.

dis.dis(del_by_pop) prints the following:

  2           0 LOAD_FAST                0 (mylist)
              3 LOAD_ATTR                0 (pop)
              6 LOAD_CONST               2 (-1)
              9 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             12 POP_TOP
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE

dis.dis(del_by_del) prints the following:

  2           0 LOAD_FAST                0 (mylist)
              3 LOAD_CONST               2 (-1)
              6 DELETE_SUBSCR
              7 LOAD_CONST               0 (None)
             10 RETURN_VALUE

del has less work to do because it doesn't need to return the popped item.

2. use a for loop instead of a while loop.

def del_for(mylist):
    for i in reversed(mylist):
        if not i:
            del mylist[-1]
        else:
            break

3. don't use del at all, just slice the list once you've found the position of the last non-zero item

def del_for(mylist):
    for i, j in enumerate(reversed(mylist)):
        if j:
            mylist = mylist[:-1*i]
            break
like image 114
Haleemur Ali Avatar answered Mar 28 '23 20:03

Haleemur Ali