Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language


 
 
Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

Python Programming Language

Looping over lists


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?

Cheers
   Tommy

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

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.

--
In friendship,
prad

                                      ... with you on your journey
Towards Freedom
http://www.towardsfreedom.com (website)
Information, Inspiration, Imagination - truly a site for soaring I's

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

Tommy Grav <t@mac.com> writes:
> 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]

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

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

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

On Fri, 4 May 2007 19:26:17 -0700, a@mac.com (Alex Martelli)
declaimed the following in comp.lang.python:

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

        Ah, but wouldn't the cleaner Python be something like

>>> a = [1, 2, 3, 4, 5, 3, 6]  #just to confuse matters
>>> for pos, val in enumerate(a):

...     for v2 in a[pos+1:]:
...             print val, v2
...            
1 2
1 3
1 4
1 5
1 3
1 6
2 3
2 4
2 5
2 3
2 6
3 4
3 5
3 3
3 6
4 5
4 3
4 6
5 3
5 6
3 6

--
        Wulfraed        Dennis Lee Bieber               KD6MOG
        wlfr@ix.netcom.com              wulfr@bestiaria.com
                HTTP://wlfraed.home.netcom.com/
        (Bestiaria Support Staff:               web-a@bestiaria.com)
                HTTP://www.bestiaria.com/
I think the for i in range() is more readable (Maybe because I'm
coming from a c-style syntax language background) -  but what would
the benefits of using enumerate be (other that being more . . .
pythonesque?)

On 5/5/07, Dennis Lee Bieber <wlfr@ix.netcom.com> wrote:

On May 5, 3:15 am, kaens <apatheticagnos@gmail.com> wrote:

> I think the for i in range() is more readable (Maybe because I'm
> coming from a c-style syntax language background) -  but what would
> the benefits of using enumerate be (other that being more . . .
> pythonesque?)

It doesn't create a whole new list just for iterating.

Dustan <DustanGro@gmail.com> writes:
> > I think the for i in range() is more readable (Maybe because I'm
> > coming from a c-style syntax language background) -  but what would
> > the benefits of using enumerate be (other that being more . . .
> > pythonesque?)

> It doesn't create a whole new list just for iterating.

That's what xrange is for.

Dustan <DustanGro@gmail.com> wrote:
> On May 5, 3:15 am, kaens <apatheticagnos@gmail.com> wrote:
> > I think the for i in range() is more readable (Maybe because I'm
> > coming from a c-style syntax language background) -  but what would
> > the benefits of using enumerate be (other that being more . . .
> > pythonesque?)

> It doesn't create a whole new list just for iterating.

As the example list was of length 5, that's not all that important in
this case.  In cases where it _is_ crucial, you can use xrange.

The performance of the various ways of looping is substantially the
same:

$ python -mtimeit -s'n=5; a=n*[23]' 'for i in range(n): x=a[i]'
1000000 loops, best of 3: 1.4 usec per loop
$ python -mtimeit -s'n=5; a=n*[23]' 'for i in xrange(n): x=a[i]'
1000000 loops, best of 3: 1.18 usec per loop
$ python -mtimeit -s'n=5; a=n*[23]' 'for i,v in enumerate(a): x=v'
1000000 loops, best of 3: 1.49 usec per loop
$

Here, xrange is minutely faster and enumerate slower, but each speed
difference "in the noise".  Focusing on clarity is thus well warranted.

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

> > >         Ah, but wouldn't the cleaner Python be something like

> > > >>> a = [1, 2, 3, 4, 5, 3, 6]   #just to confuse matters
> > > >>> for pos, val in enumerate(a):
> > > ...     for v2 in a[pos+1:]:
> > > ...             print val, v2

This "breaks symmetry", by using enumerate in the outer loop and a slice
in the inner loop; the symmetrical construction of using range in both
loops is a big conceptual/clarity win -- the reader of the code needs to
"grasp" one fewer concept (locally).  Using xrange in both loops would
be just as good from this POV.

Alex

En Sat, 05 May 2007 05:15:32 -0300, kaens <apatheticagnos@gmail.com>  
escribi:

> I think the for i in range() is more readable (Maybe because I'm
> coming from a c-style syntax language background) -  but what would
> the benefits of using enumerate be (other that being more . . .
> pythonesque?)

If you want to iterate over a sequence and process each item, you could do  
this (as one would do in C):

for i in range(len(values)):
   dosomethingwith(values[i])

Problems: values[i] gets translated into values.__getitem__(i), and that  
requires a lookup for the __getitem__ method and a function call; and you  
don't actually need the index i, but it's created anyway.
In this case the best (and fastest) way in Python is:

for item in values:
   dosomethingwith(item)

No spurious variable, no method lookup, no aditional function call. But  
what if you need *also* the index? On earlier Python versions one had to  
go back to the first method; enumerate() was made just for this case:

for i, item in enumerate(values):
   dosomethingwith(item, i)

You get all the advantages of the iterator approach plus the index  
available.

--
Gabriel Genellina

Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc