2

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

My python program...

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

    print(mont[0])

main()

This is what I get when running it...

Traceback (most recent call last):
  File "/Users/hunterjamesnelson/Documents/bruceArray.py", line 9, in <module>
    main()
  File "/Users/hunterjamesnelson/Documents/bruceArray.py", line 3, in main
    mont[0] = "bnkj1",
IndexError: list assignment index out of range
>>> 

Thanks!

1
  • Like the error message indicates, in Python these are lists; "array", to us, means something very different and less often used. Commented Feb 3, 2014 at 23:31

4 Answers 4

6

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Or in his case just mont = ['bnkj1', 'bnkj2', 'bnkj3'].
3

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.

Comments

1
def main():
    mont = []           # <- this is a zero-length list
    mont[0] = "bnkj1"   # <- there is no mont[0] to assign to

Comments

0

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

def main():
    mont = ["bnkj1", "bnkj2", "bnkj3"]
    print(mont[0])

main()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.