-3

I keep getting the error message IndexError: list assignment index out of range 

schedule = []
for i in range(18):
  schedule.append( set() )

  schedule[1] = { ('LAR','CP'), ('KCC','JJ'), ('BR','MD') }

why isn't this working?

edit: meant for schedule[1] not schedule[18]

VROLL
  • 9
  • 4
  • 2
    because on the first iteration of your for-loop, there is no index 18, so trying to assign to that list index will throw an error. – juanpa.arrivillaga Oct 18 '19 at 17:13
  • 1
    Remember that index starts at 0, so if you add 18 to a blank list, you have indexes from 0 through 17 (length minus 1). – MyNameIsCaleb Oct 18 '19 at 17:16
  • 1
    Your edit does not have an error when I run it as is. Make sure to unindent it before pasting that code so it doesn't run on every loop, in which case you'll throw an error on the first loop because only index 0 exists at that point. – MyNameIsCaleb Oct 18 '19 at 17:18
  • 1
    @juanpa.arrivillaga answer still applies after your edit. In the first iteration of your loop, there is no index 1. Indices start at zero – zachdj Oct 18 '19 at 17:18

1 Answers1

-3

Take the final assignment out of the loop.

schedule = []
for i in range(18):
  schedule.append( set() )

schedule[1] = { ('LAR','CP'), ('KCC','JJ'), ('BR','MD') }

Easier way to do what I think you're trying to do:

# Make the list of empty sets:
schedule = [set()] * 18
# or
schedule = [set() for _ in range(18)]

# Then you assign the value in the list at index 1 to the set you want:
schedule[1] = { ('LAR','CP'), ('KCC','JJ'), ('BR','MD') }

Edit: question changed and addressing comments.

it's-yer-boy-chet
  • 1,917
  • 2
  • 12
  • 21
  • 2
    The last value in `range(18)` will be 17, so `schedule[18]` will fail. – Thierry Lathuille Oct 18 '19 at 17:16
  • 2
    You pasted the same code that exists there minus an indent. Your answer doesn't explain what is wrong or what change you made and why. – MyNameIsCaleb Oct 18 '19 at 17:20
  • what do you mean by final assignment? – VROLL Oct 18 '19 at 17:24
  • You are assigning a value in a list `list[index] = ...`. This was happening in the loop in the question. I have taken it out of the loop in my answer. Indentations are very significant. Your code says to do that assignment 18 times, and returns an error because the index (`1`) doesn't exist the first time you try to assign it to a value. – it's-yer-boy-chet Oct 18 '19 at 17:26