Looping over lists

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat May 5 02:06:14 EDT 2007


In <mailman.7302.1178333181.32031.python-list at python.org>, 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

But only if the elements in the list are unique.  And the runtime is
suboptimal because `index()` is doing a linear search -- the outer loop
becomes slower and slower with each iteration.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list