Looping over lists

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tommy Grav

    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
  • Alex Martelli

    #2
    Re: Looping over lists

    Tommy Grav <tgrav@mac.comw rote:
    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

    Comment

    • Peter Otten

      #3
      Re: Looping over lists

      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(ite ms):
      items = list(items)
      while items:
      a = items.pop(0)
      for b in items:
      print a, b

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

      Peter

      Comment

      • Paul Rubin

        #4
        Re: Looping over lists

        Tommy Grav <tgrav@mac.comw rites:
        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]

        Comment

        • kaens

          #5
          Re: Looping over lists

          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 <wlfraed@ix.net com.comwrote:
          On Fri, 4 May 2007 19:26:17 -0700, aleax@mac.com (Alex Martelli)
          declaimed the following in comp.lang.pytho n:
          >
          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
          wlfraed@ix.netc om.com wulfraed@bestia ria.com

          (Bestiaria Support Staff: web-asst@bestiaria. com)

          --

          >

          Comment

          • Dustan

            #6
            Re: Looping over lists

            On May 5, 3:15 am, kaens <apatheticagnos ...@gmail.comwr ote:
            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.
            On 5/5/07, Dennis Lee Bieber <wlfr...@ix.net com.comwrote:
            >
            On Fri, 4 May 2007 19:26:17 -0700, a...@mac.com (Alex Martelli)
            declaimed the following in comp.lang.pytho n:
            >
            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.netc om.com wulfr...@bestia ria.com

            (Bestiaria Support Staff: web-a...@bestiaria. com)

            --
            http://mail.python.org/mailman/listinfo/python-list

            Comment

            • Paul Rubin

              #7
              Re: Looping over lists

              Dustan <DustanGroups@g mail.comwrites:
              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.

              Comment

              • Alex Martelli

                #8
                Re: Looping over lists

                Dustan <DustanGroups@g mail.comwrote:
                On May 5, 3:15 am, kaens <apatheticagnos ...@gmail.comwr ote:
                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

                Comment

                • Gabriel Genellina

                  #9
                  Re: Looping over lists

                  En Sat, 05 May 2007 05:15:32 -0300, kaens <apatheticagnos tic@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(value s)):
                  dosomethingwith (values[i])

                  Problems: values[i] gets translated into values.__getite m__(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(value s):
                  dosomethingwith (item, i)

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

                  --
                  Gabriel Genellina

                  Comment

                  Working...