List loops

Discussion in 'Python' started by Tommy Grav, Oct 9, 2007.

  1. Tommy Grav

    Tommy Grav Guest

    Hi everyone,

    I have a list of objects where I have want to do two loops.
    I want to loop over the list and inside this loop, work on all
    the elements of the list after the one being handled in the outer
    loop. I can of course do this with indexes:

    >>> alist = range(3)
    >>> for i in xrange(len(alist)):

    .... for j in xrange(i+1,len(alist)):
    .... print i,j,alist,alist[j]
    ....
    0 1 0 1
    0 2 0 2
    1 2 1 2
    >>>



    Is there a way to do this without using indexes?

    Cheers
    Tommy
     
    Tommy Grav, Oct 9, 2007
    #1
    1. Advertising

  2. Tommy Grav

    John Machin Guest

    On 10/10/2007 12:30 AM, Tommy Grav wrote:
    > Hi everyone,
    >
    > I have a list of objects where I have want to do two loops.
    > I want to loop over the list and inside this loop, work on all
    > the elements of the list after the one being handled in the outer
    > loop. I can of course do this with indexes:
    >
    > >>> alist = range(3)


    If you REALLY want this to work ONLY on lists of the form range(n), then
    say so. Otherwise give a generic example e.g. alist = ['foo', 42,
    3.14159] so that the channel is not clogged with red-herring responses :)

    > >>> for i in xrange(len(alist)):

    > ... for j in xrange(i+1,len(alist)):
    > ... print i,j,alist,alist[j]
    > ...
    > 0 1 0 1
    > 0 2 0 2
    > 1 2 1 2
    > >>>

    >
    >
    > Is there a way to do this without using indexes?
    >


    Probably not efficiently, if your list size is huge and you want to
    avoid making copies of sub-lists e.g. alist[i+1:].

    A somewhat more efficient version of your code:
    n = len(any_old_list)
    for i in xrange(n-1):
    # n-1 avoids possible problems if you need to use i here
    for j in xrange(i+1, n):
    # etc

    How big is n likely to be?
     
    John Machin, Oct 9, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. roopa
    Replies:
    6
    Views:
    755
    Jerry Coffin
    Aug 27, 2004
  2. Replies:
    10
    Views:
    512
    Caleb Hattingh
    Feb 8, 2005
  3. Hamilton, William

    RE: List loops

    Hamilton, William, Oct 9, 2007, in forum: Python
    Replies:
    2
    Views:
    295
    Bill Hamilton
    Oct 10, 2007
  4. Carlos Grohmann
    Replies:
    11
    Views:
    912
    sturlamolden
    Dec 19, 2009
  5. Me
    Replies:
    2
    Views:
    247
Loading...

Share This Page