all pairs of items in a list without indexing?
Alex Martelli
aleaxit at yahoo.com
Wed Sep 29 09:50:46 EDT 2004
Steven Bethard <steven.bethard at gmail.com> wrote:
...
> for i, item1 in enumerate(l):
> for item2 in l[i+1:]:
> (item1, item2)
>
> but that seems like a lot of wasteful list slicing...
Sorry, I don't get it: what's wasteful about it? Do you mean in terms
of performance?
With slicing:
kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(x,y) for i,x
in enumerate(l) for y in l[i+1:]]'
10 loops, best of 3: 1.43e+05 usec per loop
kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(x,y) for i,x
in enumerate(l) for y in l[i+1:]]'
10 loops, best of 3: 1.41e+05 usec per loop
With xrange(len(...:
kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(l[i],l[j])
for i in xrange(len(l)) for j in xrange(i+1,len(l))]'
10 loops, best of 3: 1.61e+05 usec per loop
kallisti:~/cb alex$ python2.4 timeit.py -s'l=range(333)' '[(l[i],l[j])
for i in xrange(len(l)) for j in xrange(i+1,len(l))]'
10 loops, best of 3: 1.62e+05 usec per loop
You could use itertools.islice(l,i+1,len(l)) instead of l[i+1:], but in
my tests, in this particular case, itertools appears to be slower than
plain old slicing, albeit not by much -- about 1.45 to 1.46 vs plain
slicing's 1.42 or so, and xrange's 1.61 or so.
But maybe you can clarify the 'wasteful' observation better!
Alex
More information about the Python-list
mailing list