471,337 Members | 1,167 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,337 software developers and data experts.

List loops

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:
>>alist = range(3)
for i in xrange(len(alist)):
.... for j in xrange(i+1,len(alist)):
.... print i,j,alist[i],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

Oct 9 '07 #1
1 1028
On 10/10/2007 12:30 AM, Tommy Grav wrote:
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:
>>alist = range(3)
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 i in xrange(len(alist)):
... for j in xrange(i+1,len(alist)):
... print i,j,alist[i],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?
Oct 9 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

23 posts views Thread by Fuzzyman | last post: by
9 posts views Thread by Neuruss | last post: by
35 posts views Thread by Will Stuyvesant | last post: by
90 posts views Thread by Christoph Zwerschke | last post: by
32 posts views Thread by Robin Becker | last post: by
77 posts views Thread by Ville Vainio | last post: by
13 posts views Thread by Joel Koltner | last post: by
9 posts views Thread by Ampedesign | last post: by
reply views Thread by Hatem Nassrat | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.