how to break a for loop?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Feb 21 07:42:17 EST 2006


This time it seems that using itertools gives slower results, this is
the test code:

import itertools as it
from operator import __not__

def trim_leading_zeros(seq):
    if not seq:
        return seq
    for pos, el in enumerate(seq):
        if el != 0:
            break
    if seq[pos] == 0:
        del seq[:]
        return seq
    return seq[pos:]

def trim_leading_zeros2(seq):
    seq[:] = it.dropwhile(__not__, seq)
    return seq

data = ([0,0,0,0,0,1,2,3,4],
        [1,2,3,4],
        [0,1],
        [0,0,0],
        [0,0,0,1],
        [])

for l in data:
    print l, trim_leading_zeros(l), trim_leading_zeros2(l)

from time import clock
n = 3 * 10**5

l = [0] * n + [1] * n
t = clock()
trim_leading_zeros(l)
print round(clock()-t, 2), "s"

l = [0] * n + [1] * n
t = clock()
trim_leading_zeros2(l)
print round(clock()-t, 2), "s"

Gives this output on my PC:

[0, 0, 0, 0, 0, 1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
[0, 1] [1] [1]
[0, 0, 0] [] []
[0, 0, 0, 1] [1] [1]
[] [] []
0.3 s
2.86 s

Bye,
bearophile




More information about the Python-list mailing list