Search code examples
pythonlistrangeoutindex-error

Python - Trying to transfer data between nested lists (IndexError: list assignment index out of range)


I am aware of what it means to be out of range when indexing, but I am struggling to see why my code is generating this error...

import random


howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0, howMany): 
    newList[i] = oldList[random.randint(0, len(oldList)-1)] # subtract one 

Solution

  • You are getting the error because newList is empty (its length is 0). You are trying to access elements in it using an index, but there are no indices. Here's a simpler example of what's happening:

    >>> newList = []
    >>> i = 0
    >>> newList[i] = 1
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list assignment index out of range
    

    What you want to do is use append():

    import random
    
    
    howMany = random.randint(1,3)
    oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
    newList = []
    for i in range(0,howMany): 
        newList.append(oldList[random.randint(0, len(oldList)-1)]) # subtract one