Python array not working

后端 未结 4 553
暗喜
暗喜 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:22

    Python doesn't allow you to append just by assigning to an index out of the range of the list. You need to use .append instead:

    def main():
        mont = []
        mont.append("bnkj1")
        mont.append("bnkj2")
        mont.append("bnkj3")
    
        print(mont[0])
    
    main()
    
    0 讨论(0)
  • 2021-01-22 10:22
    def main():
        mont = []           # <- this is a zero-length list
        mont[0] = "bnkj1"   # <- there is no mont[0] to assign to
    
    0 讨论(0)
  • 2021-01-22 10:35

    This avoids building an empty list and then appending to it thrice.

    def main():
        mont = ["bnkj1", "bnkj2", "bnkj3"]
        print(mont[0])
    
    main()
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题