List loops

John Machin sjmachin at lexicon.net
Tue Oct 9 18:05:49 EDT 2007


On 10/10/2007 1:00 AM, Chris Mellon wrote:
> On 10/9/07, Tommy Grav <tgrav at mac.com> 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)
>>  >>> 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?
>>
> 
>>>> for idx, i in enumerate(alist):
> ...     for jdx, j in enumerate(range(1,4)):

# BZZZZZZT Holy hardwired hogwash, Batman!

> ...         print idx, jdx, i, j
> ...
> 0 0 0 1
> 0 1 0 2
> 0 2 0 3
# BZZZZZZZT no such animal as 3
> 1 0 1 1
# BZZZZZZZT "after"???
> 1 1 1 2
> 1 2 1 3
# BZZZZZZZT no such animal as 3
> 2 0 2 1
> 2 1 2 2
> 2 2 2 3
# BZZZZZZZT "after"???



More information about the Python-list mailing list