Search code examples
python-3.xlistindex-error

Getting error in list assignment about index?


I recently started to study Python, and as I was trying to run a code from a book (with my modification) I got the error:

IndexError: list assignment index out of range
in : `Names[len(Names)]=name`

I read some questions with this error on web but can't figure it out.

Names=[]
num=0
name=''
while True :

    print('Enter the name of person '+str(len(Names)+1) + '(or Enter nothing to stop)')
    name=input()

    if name == '' :
        break

    Names[len(Names)]=name
print('the person names are:')

for num in range(len(Names)+1) :
    print('   '+Names[num])

Solution

  • You can not access out of range index Ex:

    >>> l = [1,2,3]
    >>> l = [0,1,2]
    >>> l[3] = "New"
    
    Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
        l[3] = "New"
    IndexError: list assignment index out of range
    

    For that, you have to append new data to the list.

    >>> l.append("new")
    >>> l
    [0, 1, 2, 'new']
    

    You can try:

    Names=[]
    num=0
    name=''
    while True :
    
        print('Enter the name of person '+str(len(Names)+1) + '(or Enter nothing to stop)')
        name=input()
    
        if name == '' :
            break
    
        Names.append(name)
    print('the person names are:')
    
    for num in range(len(Names)) :
        print('   '+Names[num])