python set list index value that doesn 27t exist

Solutions on MaxInterview for python set list index value that doesn 27t exist by the best coders in the world

showing results for - "python set list index value that doesn 27t exist"
Jessica
01 Aug 2016
1def SetList(list_, index, value):
2      try:
3      	  # Try to input the index into the list
4          list_[index] = value
5		  return list_
6      except IndexError:
7          # Create new 'None' items into the list for placeholder
8          for _ in range(index - len(list_) + 1):
9              list_.append(None)
10          # Now that the index has been initialized you can set the
11		  # index the value you want
12          list_[index] = value
13          return list_
14
15# Use SetList to put the value you want to the index you want in the 
16# specified list
17myList = [0, 1, 2, 3]
18newList = SetList(myList, 7, 10)
19print(newList)
20# output: [0, 1, 2, 3, None, None, None, 10]
21
similar questions