Python 2.x gotchas and landmines

后端 未结 23 2297
北恋
北恋 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:21

    One of the biggest surprises I ever had with Python is this one:

    a = ([42],)
    a[0] += [43, 44]
    

    This works as one might expect, except for raising a TypeError after updating the first entry of the tuple! So a will be ([42, 43, 44],) after executing the += statement, but there will be an exception anyway. If you try this on the other hand

    a = ([42],)
    b = a[0]
    b += [43, 44]
    

    you won't get an error.

提交回复
热议问题