List loops

T

Tommy Grav

Hi everyone,

I have a list of objects where I have want to do two loops.
I want to loop over the list and inside this loop, work on all
the elements of the list after the one being handled in the outer
loop. I can of course do this with indexes:
.... for j in xrange(i+1,len(alist)):
.... print i,j,alist,alist[j]
....
0 1 0 1
0 2 0 2
1 2 1 2

Is there a way to do this without using indexes?

Cheers
Tommy
 
J

John Machin

Hi everyone,

I have a list of objects where I have want to do two loops.
I want to loop over the list and inside this loop, work on all
the elements of the list after the one being handled in the outer
loop. I can of course do this with indexes:

If you REALLY want this to work ONLY on lists of the form range(n), then
say so. Otherwise give a generic example e.g. alist = ['foo', 42,
3.14159] so that the channel is not clogged with red-herring responses :)
... for j in xrange(i+1,len(alist)):
... print i,j,alist,alist[j]
...
0 1 0 1
0 2 0 2
1 2 1 2

Is there a way to do this without using indexes?


Probably not efficiently, if your list size is huge and you want to
avoid making copies of sub-lists e.g. alist[i+1:].

A somewhat more efficient version of your code:
n = len(any_old_list)
for i in xrange(n-1):
# n-1 avoids possible problems if you need to use i here
for j in xrange(i+1, n):
# etc

How big is n likely to be?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top