Python 2.x gotchas and landmines

后端 未结 23 2277
北恋
北恋 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

    If you create a list of list this way:

    arr = [[2]] * 5 
    print arr 
    [[2], [2], [2], [2], [2]]
    

    Then this creates an array with all elements pointing to the same object ! This might create a real confusion. Consider this:

    arr[0][0] = 5
    

    then if you print arr

    print arr
    [[5], [5], [5], [5], [5]]
    

    The proper way of initializing the array is for example with a list comprehension:

    arr = [[2] for _ in range(5)]
    
    arr[0][0] = 5
    
    print arr
    
    [[5], [2], [2], [2], [2]]
    

提交回复
热议问题