Looping over lists

Alex Martelli aleax at mac.com
Fri May 4 22:26:17 EDT 2007


Tommy Grav <tgrav at mac.com> wrote:

> I have a list:
> 
>    a = [1., 2., 3., 4., 5.]
> 
> I want to loop over a and then
> loop over the elements in a
> that is to the right of the current
> element of the first loop
> 
> In C this would be equivalent to:
> 
> for(i = 0; i < n; i++) {
>     for(j=i+1; j < n; j++) {
>       print a[i], a[j]
> 
> and should yield:
>     1.   2.
>     1.   3.
>     1.   4.
>     1.   5.
>     2.   3.
>     2.   4.
>     2.   5.
>     3.   4.
>     3.   5.
>     4.   5.
> 
> Can anyone help me with the right approach for this
> in python?

Closes to the C++ code would be:

for i in range(n):
    for j in range(i+1, n):
        print a[i], a[j]


Alex



More information about the Python-list mailing list