Friday, August 20, 2004

Things I didn't know Python could do


>>> class x:
... y = 0
...
>>> for x.y in range(5):
... print x.y,
...
0 1 2 3 4
>>>
>>> x = [None]
>>> for x[0] in range(5):
... print x,
...
[0] [1] [2] [3] [4]
>>>

4 comments:

  1. Another interesting one is:

    def f(a, (b, c)): print a, b, c

    f(1, [2, 3]) # --> 1 2 3

    f(1, 2) # --> TypeError: unpack non-sequence

    ReplyDelete
  2. To go along with Ian sharing the not-well-known fact that tuple unpacking works in more places than as an lvalue, I thought I'd share one of my favorite subtle things to do:

    >>> x = [1]
    >>> y, = x
    >>> print y
    1

    ReplyDelete
  3. I usually spell that 'y ,= x' for consistency with other augmented assignment operations :-)

    ReplyDelete
  4. ewwwwwwwwwwwwwwwwwwwwwwwwwwwwww

    ReplyDelete