3

IndexError: list assignment index out of range in python What am i doing wrong. I am an newbie

actual_ans_dict = []
for data in prsnobj.result:
    actual_ans_dict[data[0]] = data[1]
    print actual_ans_dict
2
  • 1
    What is the point of calling a list a dict? Commented Dec 4, 2013 at 10:07
  • 1
    [] for lists, {} for dictionaries Commented Dec 4, 2013 at 10:19

2 Answers 2

5

actual_ans_dict is an empty list. You are trying to set a value to actual_ans_dict[data[0]] but an element with this index doesn't exist.
You can change the type of actual_ans_dict to dict:

actual_ans_dict = {}
for data in prsnobj.result:
    actual_ans_dict[data[0]] = data[1]
    print actual_ans_dict
Sign up to request clarification or add additional context in comments.

Comments

1

This is because your actual_ans_dict is empty, which means, it has not any indexes yet.

actual_ans_dict = [None]*max([data[0] for data in prsnobj.result])  # not very pythonic, actualy
for data in prsnobj.result:
    actual_ans_dict[data[0]] = data[1]
    print actual_ans_dict

This will give you the ability to assign a value to a particular index. There is a slightly more correct and shorter way to do it:

actual_ans_dict = [data[1] for data in prsnobj.result]

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.