How to make a reverse for loop in python?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Alex Snast

    How to make a reverse for loop in python?

    Hello

    I'm new to python and i can't figure out how to write a reverse for
    loop in python

    e.g. the python equivalent to the c++ loop

    for (i = 10; i >= 0; --i)
  • Thoma

    #2
    Re: How to make a reverse for loop in python?

    Alex Snast a écrit :
    Hello
    >
    I'm new to python and i can't figure out how to write a reverse for
    loop in python
    >
    e.g. the python equivalent to the c++ loop
    >
    for (i = 10; i >= 0; --i)
    for (i = 0; i < 10; i--) -for i in range(10):

    for (i = 10; i >= 0; --i) -for i in range(10,-1,-1):

    Thoma

    Comment

    • Mensanator

      #3
      Re: How to make a reverse for loop in python?

      On Sep 20, 11:16�am, Alex Snast <asn...@gmail.c omwrote:
      Hello
      >
      I'm new to python and i can't figure out how to write a reverse for
      loop in python
      >
      e.g. the python equivalent to the c++ loop
      >
      for (i = 10; i >= 0; --i)
      >>for i in xrange(10,-1,-1): print i,
      10 9 8 7 6 5 4 3 2 1 0

      Note the starting number is 10, the ending
      number is -1 because you want to include 0
      and the step size is -1.

      Comment

      • Duncan Booth

        #4
        Re: How to make a reverse for loop in python?

        Alex Snast <asnast@gmail.c omwrote:
        Hello
        >
        I'm new to python and i can't figure out how to write a reverse for
        loop in python
        >
        e.g. the python equivalent to the c++ loop
        >
        for (i = 10; i >= 0; --i)
        >
        The exact equivalent would be:

        for i in range(10, -1, -1): print i

        except you virtually never want to do that in Python. Don't expect just to
        translate statement by statement from one language to another: normally in
        Python you will iterate directly over the sequence you want to process
        rather than trying to count loop indices with all the telegraph pole errors
        that result.

        The usual way to iterate over a sequence in reverse is:

        for x in reversed(seq): print x

        although if you know it is a list, string or other object that supports
        extended slicing you can also do:

        for x in seq[::-1]: print x

        this may be less clear than using 'reversed', but does allow you to specify
        an explicit start, stop and step if you want to do only part of the
        sequence.

        Comment

        • Simon Brunning

          #5
          Re: How to make a reverse for loop in python?

          2008/9/20 Alex Snast <asnast@gmail.c om>:
          I'm new to python and i can't figure out how to write a reverse for
          loop in python
          >
          e.g. the python equivalent to the c++ loop
          >
          for (i = 10; i >= 0; --i)
          for i in range(10, 0, -1):
          print i

          --
          Cheers,
          Simon B.

          Comment

          • Fredrik Lundh

            #6
            Re: How to make a reverse for loop in python?

            Alex Snast wrote:
            I'm new to python and i can't figure out how to write a reverse for
            loop in python
            >
            e.g. the python equivalent to the c++ loop
            >
            for (i = 10; i >= 0; --i)
            use range with a negative step:

            for i in range(10-1, -1, -1):
            ...

            or just reverse the range:

            for i in reversed(range( 10)):
            ...

            (the latter is mentioned in the tutorial, and is the second hit if you
            google for "python reverse for loop")

            </F>

            Comment

            • Gary Herron

              #7
              Re: How to make a reverse for loop in python?

              Alex Snast wrote:
              Hello
              >
              I'm new to python and i can't figure out how to write a reverse for
              loop in python
              >
              e.g. the python equivalent to the c++ loop
              >
              for (i = 10; i >= 0; --i)
              --

              >
              What are you trying to loop through?

              If it's the contents of a list, you can reverse the list (in place) first:

              L = [1,2,3]
              L.reverse()
              for item in L:
              print item

              Or you can create a new reversed (copy of the original) list and iterate
              through it

              for item in reversed(L):
              print item

              If it's just a sequence of numbers you want to generate:

              range(3) generates a forward list [0,1,2], and
              range(3,0,-1) generates a backward list [2,1,0]

              so

              for i in range(11,0,-1):

              might be what you want.


              If your list is huge, consider xrange rather than range.


              And as always, you could just roll your own index manipulation:

              i = 10
              while i >=0:
              # do whatever
              i -= 1




              Gary Herron


              Comment

              • Fredrik Lundh

                #8
                Re: How to make a reverse for loop in python?

                Fredrik Lundh wrote:
                >e.g. the python equivalent to the c++ loop
                >>
                >for (i = 10; i >= 0; --i)
                >
                use range with a negative step:
                >
                for i in range(10-1, -1, -1):
                ...
                >
                or just reverse the range:
                >
                for i in reversed(range( 10)):
                ...
                (and to include the 10 in the range, add one to the 10 above)

                </F>

                Comment

                • Peter Otten

                  #9
                  Re: How to make a reverse for loop in python?

                  Gary Herron wrote:
                  Or you can create a new reversed (copy of the original) list and iterate
                  through it
                  >
                  for item in reversed(L):
                    print item
                  It's not a copy, it's a view:
                  >>items = [1,2,3]
                  >>r = reversed(items)
                  >>items[:] = "abc"
                  >>for item in r: print item
                  ....
                  c
                  b
                  a

                  Peter

                  Comment

                  • bearophileHUGS@lycos.com

                    #10
                    Re: How to make a reverse for loop in python?

                    Duncan Booth:
                    e.g. the python equivalent to the c++ loop
                    for (i = 10; i >= 0; --i)
                    >
                    The exact equivalent would be:
                    for i in range(10, -1, -1): print i
                    I'd use xrange there. Anyway, I have always felt that Python syntax
                    not easy to understand at first sight, expecially when you try to
                    convert a bit more complex inverted for loops from/to C to/from
                    Python. It's one of the few cases where (for example) Pascal (loop)
                    syntax wins a bit over Python syntax :-)

                    Bye,
                    bearophile

                    Comment

                    • Alex Snast

                      #11
                      Re: How to make a reverse for loop in python?

                      On Sep 20, 8:13 pm, bearophileH...@ lycos.com wrote:
                      Duncan Booth:
                      >
                      e.g. the python equivalent to the c++ loop
                      for (i = 10; i >= 0; --i)
                      >
                      The exact equivalent would be:
                              for i in range(10, -1, -1): print i
                      >
                      I'd use xrange there. Anyway, I have always felt that Python syntax
                      not easy to understand at first sight, expecially when you try to
                      convert a bit more complex inverted for loops from/to C to/from
                      Python. It's one of the few cases where (for example) Pascal (loop)
                      syntax wins a bit over Python syntax :-)
                      >
                      Bye,
                      bearophile
                      That's a lot of responses guys. Thanks a lot i think i got it.
                      Another question, are there any pointers in python (or iterators) for
                      when i use
                      a data structure that doesn't support random access?

                      Thanks again, Alex

                      Comment

                      • Alex Snast

                        #12
                        Re: How to make a reverse for loop in python?

                        On Sep 20, 8:13 pm, bearophileH...@ lycos.com wrote:
                        Duncan Booth:
                        >
                        e.g. the python equivalent to the c++ loop
                        for (i = 10; i >= 0; --i)
                        >
                        The exact equivalent would be:
                                for i in range(10, -1, -1): print i
                        >
                        I'd use xrange there. Anyway, I have always felt that Python syntax
                        not easy to understand at first sight, expecially when you try to
                        convert a bit more complex inverted for loops from/to C to/from
                        Python. It's one of the few cases where (for example) Pascal (loop)
                        syntax wins a bit over Python syntax :-)
                        >
                        Bye,
                        bearophile
                        Another quick question please, is the List data structure just a
                        dynamic array? If so how can you use static size array, linked list,
                        AVL trees etcetera.

                        Comment

                        • Christian Heimes

                          #13
                          Re: How to make a reverse for loop in python?

                          Alex Snast wrote:
                          Another quick question please, is the List data structure just a
                          dynamic array? If so how can you use static size array, linked list,
                          AVL trees etcetera.
                          You should treat Python lists as an opaque item. You shouldn't concern
                          yourself with the implementation details. Python lists are fast and
                          optimized for most use cases. Unless you have specific needs for highly
                          specialized data types, use lists.

                          Just *don't* try to abuse lists by creating fancy stuff e.g. linked
                          lists. The memory overhead is going to kill your app.

                          Christian

                          Comment

                          • Gabriel Genellina

                            #14
                            Re: How to make a reverse for loop in python?

                            En Sat, 20 Sep 2008 20:27:41 -0300, Alex Snast <asnast@gmail.c omescribió:
                            Another quick question please, is the List data structure just a
                            dynamic array? If so how can you use static size array, linked list,
                            AVL trees etcetera.
                            Yes, lists are implemented as dynamic arrays (but you shouldn't care about
                            it). "Textbook" linked lists are good for a CS course, but useless in most
                            usual circumstances (think of memory fragmentation). There are AVL trees
                            implemented in Python, but not built in.
                            Read the Python Tutorial specially this section

                            You may be interested in the collections module too
                            Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.,,...


                            --
                            Gabriel Genellina

                            Comment

                            • bearophileHUGS@lycos.com

                              #15
                              Re: How to make a reverse for loop in python?

                              Christian Heimes:
                              Unless you have specific needs for highly specialized data types, use lists.
                              There's also the collections.deq ue for other related purposes.

                              (I suggest people willing to look at some nice C code to read the
                              sources of deque, Hettinger has created some refined code, very
                              readable).

                              Bye,
                              bearophile

                              Comment

                              Working...