for: else: - any practical uses for the else clause?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • metaperl.etc@gmail.com

    for: else: - any practical uses for the else clause?

    A very old thread:


    discusses the optional "else:" clause of the for statement.

    I'm wondering if anyone has ever found a practical use for the else
    branch?

  • skip@pobox.com

    #2
    Re: for: else: - any practical uses for the else clause?


    metaperlI'm wondering if anyone has ever found a practical use for the
    metaperlelse branch?

    Yeah, I use it from time to time:

    for foo in bar:
    if foo matches some condition:
    print "sail to tahiti!"
    break
    else:
    print "abandon ship!"

    Skip

    Comment

    • Amaury Forgeot d'Arc

      #3
      Re: for: else: - any practical uses for the else clause?

      metaperl.etc@gm ail.com a écrit :
      A very old thread:

      >
      discusses the optional "else:" clause of the for statement.
      >
      I'm wondering if anyone has ever found a practical use for the else
      branch?
      >
      I use it regularly in contructs like:

      for value in someList:
      if someCondition(v alue):
      print "a matching item was found"
      break
      else:
      print "no matching item"
      return False

      # ... continue with value

      --
      Amaury

      Comment

      • Bruno Desthuilliers

        #4
        Re: for: else: - any practical uses for the else clause?

        metaperl.etc@gm ail.com a écrit :
        A very old thread:

        >
        discusses the optional "else:" clause of the for statement.
        >
        I'm wondering if anyone has ever found a practical use for the else
        branch?
        >
        <aol>
        Just like Skip and Amaury...
        </aol>

        Comment

        • Fuzzyman

          #5
          Re: for: else: - any practical uses for the else clause?


          Amaury Forgeot d'Arc wrote:
          metaperl.etc@gm ail.com a écrit :
          A very old thread:


          discusses the optional "else:" clause of the for statement.

          I'm wondering if anyone has ever found a practical use for the else
          branch?
          >
          I use it regularly in contructs like:
          >
          for value in someList:
          if someCondition(v alue):
          print "a matching item was found"
          break
          else:
          print "no matching item"
          return False
          >
          # ... continue with value
          Me too...

          Same with while loops.

          Fuzzyman


          --
          Amaury

          Comment

          • Ben Sizer

            #6
            Re: for: else: - any practical uses for the else clause?

            skip@pobox.com wrote:
            metaperlI'm wondering if anyone has ever found a practical use for the
            metaperlelse branch?
            >
            Yeah, I use it from time to time:
            >
            for foo in bar:
            if foo matches some condition:
            print "sail to tahiti!"
            break
            else:
            print "abandon ship!"
            As a C++ programmer (which I'm sure undermines my argument before
            you've even read it...), this feels 'backwards' to me. Although I am no
            purist, the 'else' typically implies failure of a previous explicit
            condition, yet in this case, it's executed by default, when the
            previous clause was successfully executed. It would seem more natural
            if the else clause was triggered by 'bar' being empty, or even if the
            loop was explicitly broken out of, though I'm sure that would make the
            construct much less useful.

            --
            Ben Sizer

            Comment

            • Sion Arrowsmith

              #7
              Re: for: else: - any practical uses for the else clause?

              Ben Sizer <kylotan@gmail. comwrote:
              >skip@pobox.c om wrote:
              >Yeah, I use it from time to time:
              >>
              > for foo in bar:
              > if foo matches some condition:
              > print "sail to tahiti!"
              > break
              > else:
              > print "abandon ship!"
              >
              >As a C++ programmer (which I'm sure undermines my argument before
              >you've even read it...), this feels 'backwards' to me. Although I am no
              >purist, the 'else' typically implies failure of a previous explicit
              >condition, yet in this case, it's executed by default, when the
              >previous clause was successfully executed. It would seem more natural
              >if the else clause was triggered by 'bar' being empty, [ ... ]
              It does:
              >>for foo in []:
              .... print foo
              .... else:
              .... print 'else'
              ....
              else

              I think it's clearer to see by comparing while with if:

              if False:
              do nothing
              else:
              do something

              while False:
              do nothing
              else:
              do something

              and getting to the for behaviour from while is trivial.

              That said, I've not had much call for it and was kind of surprised to
              find myself writing a genuine for ... else the other week. But it was
              the obvious way to do the task at hand, and I was happy it was there.

              --
              \S -- siona@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
              ___ | "Frankly I have no feelings towards penguins one way or the other"
              \X/ | -- Arthur C. Clarke
              her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

              Comment

              • metaperl

                #8
                Re: for: else: - any practical uses for the else clause?

                Actually right after posting this I came up with a great usage. I use
                meld3 for my Python based dynamic HTML generation. Whenever I plan to
                loop over a tree section I use a for loop, but if there is no data to
                iterate over, then I simply remove that section from the tree or
                populate it with a "no data" message.

                Comment

                • Klaas

                  #9
                  Re: for: else: - any practical uses for the else clause?

                  metaperl wrote:
                  Actually right after posting this I came up with a great usage. I use
                  meld3 for my Python based dynamic HTML generation. Whenever I plan to
                  loop over a tree section I use a for loop, but if there is no data to
                  iterate over, then I simply remove that section from the tree or
                  populate it with a "no data" message.
                  else: does not trigger when there is no data on which to iterate, but
                  when the loop terminated normally (ie., wasn't break-ed out). It is
                  meaningless without break.

                  Python 2.4.3 (#1, Mar 29 2006, 15:37:23)
                  [GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2
                  Type "help", "copyright" , "credits" or "license" for more information.
                  >>for x in []:
                  .... print 'nothing'
                  .... else:
                  .... print 'done'
                  ....
                  done

                  -Mike

                  Comment

                  • Klaas

                    #10
                    Re: for: else: - any practical uses for the else clause?

                    Klaas wrote:
                    else: does not trigger when there is no data on which to iterate, but
                    when the loop terminated normally (ie., wasn't break-ed out). It is
                    meaningless without break.
                    Sorry, this was worded confusingly. "else: triggers when the loop
                    terminates normally, not simply in the case that there is no iterated
                    data".

                    -Mike

                    Comment

                    • Mike Klaas

                      #11
                      Re: for: else: - any practical uses for the else clause?

                      On 9/29/06, Johan Steyn <johan.steyn@gm ail.comwrote:
                      On 29 Sep 2006 11:26:10 -0700, Klaas <mike.klaas@gma il.comwrote:
                      >
                      else: does not trigger when there is no data on which to iterate, but
                      when the loop terminated normally (ie., wasn't break-ed out). It is
                      meaningless without break.
                      >
                      The else clause *is* executed when there is no data on which to iterate.
                      Your example even demonstrates that clearly:
                      Yes--there is a missing "just" in that sentence.

                      -Mike

                      Comment

                      • BJörn Lindqvist

                        #12
                        Re: for: else: - any practical uses for the else clause?

                        On 9/29/06, Johan Steyn <johan.steyn@gm ail.comwrote:
                        I agree that it is meaningless without a break statement, but I still find
                        it useful when I want to determine whether I looped over the whole list or
                        not. For example, if I want to see whether or not a list contains an odd
                        number:
                        >
                        for i in list:
                        if i % 2 == 1:
                        print "Found an odd number."
                        break
                        else:
                        print "No odd number found."
                        >
                        Without the else clause I would need to use an extra variable as a "flag"
                        and check its value outside the loop:
                        You can use generator comprehension:

                        if (i for i in list if i % 2 == 1):
                        print "Found an odd number."
                        else:
                        print "No odd number found."

                        I *think* any() should also work:

                        if any(i % 2 == 1 in list):
                        ....

                        And so on. For every use of the for/else clause there exists a better
                        alternative. Which sums up my opinion about the construct -- if you
                        are using it, there's something wrong with your code.

                        --
                        mvh Björn

                        Comment

                        • Matthew Woodcraft

                          #13
                          Re: for: else: - any practical uses for the else clause?

                          bjourne@gmail.c om wrote:
                          And so on. For every use of the for/else clause there exists a better
                          alternative. Which sums up my opinion about the construct -- if you
                          are using it, there's something wrong with your code.
                          How do you transform this?

                          height = 0
                          for block in stack:
                          if block.is_marked ():
                          print "Lowest marked block is at height", height
                          break
                          height += block.height
                          else:
                          raise SomeError("No marked block")

                          -M-

                          Comment

                          • Paul Rubin

                            #14
                            Re: for: else: - any practical uses for the else clause?

                            Matthew Woodcraft <mattheww@chiar k.greenend.org. ukwrites:
                            How do you transform this?
                            >
                            height = 0
                            for block in stack:
                            if block.is_marked ():
                            print "Lowest marked block is at height", height
                            break
                            height += block.height
                            else:
                            raise SomeError("No marked block")
                            Untested:

                            all_heights = [block.height for block in stack if block.is_marked ()]
                            if all_heights:
                            height = sum(all_heights )
                            else:
                            raise SomeError("No marked block")

                            Alternatively (lower memory usage for large list):

                            all_heights = (block.height for block in stack if block.is_marked ())
                            try:
                            height = all_heights.nex t()
                            height += sum(all_heights )
                            except StopIteration:
                            raise SomeError("No marked block")

                            Comment

                            • Sybren Stuvel

                              #15
                              Re: for: else: - any practical uses for the else clause?

                              Paul Rubin enlightened us with:
                              >height = 0
                              >for block in stack:
                              > if block.is_marked ():
                              > print "Lowest marked block is at height", height
                              > break
                              > height += block.height
                              >else:
                              > raise SomeError("No marked block")
                              >
                              all_heights = [block.height for block in stack if block.is_marked ()]
                              if all_heights:
                              height = sum(all_heights )
                              else:
                              raise SomeError("No marked block")
                              >
                              Alternatively (lower memory usage for large list):
                              >
                              all_heights = (block.height for block in stack if block.is_marked ())
                              try:
                              height = all_heights.nex t()
                              height += sum(all_heights )
                              except StopIteration:
                              raise SomeError("No marked block")
                              I must say that the for/else construct is a LOT more readable than the
                              rewritten alternatives.

                              Sybren
                              --
                              Sybren Stüvel
                              Stüvel IT - http://www.stuvel.eu/

                              Comment

                              Working...