0
arr = [1]
arr[0] = arr.pop() 

giving me IndexError: list assignment index out of range i don't understand why?

1
  • because you pop'd from the list, now the list has zero elements, then you try to assign to arr[0], but since there is not arr[0], you get the index error. Commented Aug 3, 2020 at 4:46

2 Answers 2

7

By calling arr.pop() it makes arr change to [], so after that if you try retrieving / chaging item at index 0 it will be out of range since its size is 0

Sign up to request clarification or add additional context in comments.

Comments

0

The right-hand side of an assignment statement is evaluated before the left-hand side. So the list is empty when you try to assign at index 0.

You could rewrite your code roughly as:

arr = [1]
popped = arr.pop()
arr[0] = popped

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.