Looping over lists

Peter Otten __peter__ at web.de
Sat May 5 02:00:27 EDT 2007


prad wrote:

> On Friday 04 May 2007 18:40:53 Tommy Grav wrote:
>> Can anyone help me with the right approach for this
>> in python?
> 
> for each in a:
>     for item in a[a.index(each)+1:]:
>         print each,item
> 
> will produce
> 
> 1 2
> 1 3
> 1 4
> 1 5
> 2 3
> 2 4
> 2 5
> 3 4
> 3 5
> 4 5
> 
> a.index(each) gives the index of the each value in the a list.
> then you just add 1 to it so you start at the index value beside each's
> index.

If there are equal items you may not get what you expect:
 
>>> items = [1, 2, 1.0]
>>> for a in items:
...     for b in items[items.index(a)+1:]:
...             print a, b
...
1 2
1 1.0
2 1.0
1.0 2
1.0 1.0

Peter




More information about the Python-list mailing list