Python 2.x gotchas and landmines

后端 未结 23 2280
北恋
北恋 2020-11-28 17:47

The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things sp

23条回答
  •  清酒与你
    2020-11-28 18:06

    List slicing has caused me a lot of grief. I actually consider the following behavior a bug.

    Define a list x

    >>> x = [10, 20, 30, 40, 50]
    

    Access index 2:

    >>> x[2]
    30
    

    As you expect.

    Slice the list from index 2 and to the end of the list:

    >>> x[2:]
    [30, 40, 50]
    

    As you expect.

    Access index 7:

    >>> x[7]
    Traceback (most recent call last):
      File "", line 1, in 
    IndexError: list index out of range
    

    Again, as you expect.

    However, try to slice the list from index 7 until the end of the list:

    >>> x[7:]
    []
    

    ???

    The remedy is to put a lot of tests when using list slicing. I wish I'd just get an error instead. Much easier to debug.

提交回复
热议问题