Python array not working

后端 未结 4 556
暗喜
暗喜 2021-01-22 09:40

This is so simple! Why isnt it working?!?!?

My python program...

def main():
    mont = []
    mont[0] = \"bnkj1\"
    mont[1] = \"bnkj2\"
    mont[2] =          


        
4条回答
  •  一个人的身影
    2021-01-22 10:36

    The problem is that you need to specify the list size when you initialize it to use it like you do. You get an error because the list you defined has length 0. So accessing on any index will be out of range.

    def main():
        mont = [None]*3
        mont[0] = "bnkj1"
        mont[1] = "bnkj2"
        mont[2] = "bnkj3"
    
        print(mont[0])
    
    main()
    

    alternativ you can use .append() to increase the size and adding an element.

提交回复
热议问题