1.5.2 for: else:
Gordon McMillan
gmcm at hypernet.com
Wed Jul 28 17:38:24 EDT 1999
More information about the Python-list mailing list
Wed Jul 28 17:38:24 EDT 1999
- Previous message (by thread): 1.5.2 for: else:
- Next message (by thread): 1.5.2 for: else:
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
William Tanksley wrote: > On Tue, 27 Jul 1999 21:43:00 -0500, Gordon McMillan wrote: [snip Billy's silly error and his entirely insufficient embarassment <wink>] > However, you're wrong about the best way to detect a 2 in the list > using this style. To steal the same example: > > try: > for x in [1,2,3]: > print x > if x == 2: raise neverMind > print "modern else clause here" > except neverMind: print "found two" > else: > print "another place to put the modern else clause" > > Wow, TMTOWTDI. Oops, did I say the wrong thing? > > Of course, by demonstrating both ways to do it, I'm making the code > more complex; but you can see that this solution solves the problem > quite elegantly. WIth an extra class, and 3 or 4 more lines of code, not to mention treading on the toes of all who think exceptions should only be used for exceptional conditions (or maybe it _is_ exceptional when something you wrote works <1e3 wink>). > The place to use MY definition of 'else', OTOH, is when you're > building a structure during the iteration, but the result of an > empty loop is different than the initial value the variable has to > have when going through the loop. > > Here you go. This example might convert a Python list into a Lisp > tree-list -- but to imitate Lisp (okay, it's a toy problem, I'm > cheating) an empty list produces NIL ~= None. > > var = Node(None,None) > for x in pyList: > var.car = x > var.cdr = Node() > else: > var = None Not a Lisper, but isn't what you're doing better done thusly: def test1(lst): var = None for x in lst: var = (x, var) return var print `test1([1,2,3])` print `test1([])` Produces: (3, (2, (1, None))) None > >insufferably-sanctimoniously-y'rs > > >- Gordon > > unstoppably-confidantly y'rs > > -- > -William "Billy" Tanksley so-self-righteous-without-the-winks-I-might-almost-be-mistaken -for-that-other-GM-ly y'rs - Gordon
- Previous message (by thread): 1.5.2 for: else:
- Next message (by thread): 1.5.2 for: else:
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list