Velocity Reviews > List loops

# List loops

Tommy Grav
Guest
Posts: n/a

 10-09-2007
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

John Machin
Guest
Posts: n/a

 10-09-2007
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?

 Thread Tools

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post Carlos Grohmann Python 11 12-19-2009 02:18 PM Hamilton, William Python 2 10-09-2007 11:27 PM Me Perl Misc 2 01-12-2006 05:07 PM jamesthiele.usenet@gmail.com Python 10 02-08-2005 03:53 AM roopa C++ 6 08-27-2004 06:18 PM

Advertisments