Hacker News new | past | comments | ask | show | jobs | submit login
Transforming Code into Beautiful, Idiomatic Python [video] (pyvideo.org)
54 points by s16h on July 9, 2014 | hide | past | favorite | 4 comments




After a while, he shows the example of a find function

  def find(seq, target):
    for i, value in enumerate(seq):
      if value == target
        break
    else:
      return -1
    return i
Can't you just remove the whole break and else thing and just do this?

  def find(seq, target):
    for i, value in enumerate(seq):
      if value == target:
        return i
    return -1


Your second example looks fine to me.

EDIT: My best guess as to what's going on is that they want to display the for-else idiom which could be useful in other contexts (e.g. if you don't want to return anything from inside the loop and can't break out that way.) It's a kinda surprising idiom; I had forgotten you could even do that in Python and at first thought it might be a misindentation until I realized the logic would be wrong if the else paired with if.


Yes, the trivial example can (and should) be optimized.

The point of the structure is to give an example of flagging a 'found' state, so we need to pretend there are extra mandatory steps in there, because the structure would be embedded in more complex code. He mentions this briefly in that section of the talk, see 'and number 2...' at 16:30.

Cheers!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: