Looping over lists

Peter Otten __peter__ at web.de
Sat May 5 01:43:53 EDT 2007


Tommy Grav 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?

Two more options:

def pop_combine(items):
    items = list(items)
    while items:
        a = items.pop(0)
        for b in items:
            print a, b

def enumerate_combine(items):
    for i, a in enumerate(items):
        for b in items[i+1:]:
            print a, b

Peter



More information about the Python-list mailing list