Mehrdad
Mehrdad

Reputation: 3

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])

Upvotes: 0

Views: 51

Answers (3)

taurus05
taurus05

Reputation: 2546

just use the append function to insert the new name to the existing list of names.

Syntax:-

if you want to append 'foo' to the list of existing names i.e 'Names',type Names.append('foo').

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

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])

Upvotes: 0

iBug
iBug

Reputation: 37227

Looks like you want to append something to an existing list. Why not use .append()? This won't give you the IndexError.

Names.append(name)

Another same error: You shouldn't write range(len(Names) + 1). range(len(Names)) is enough for you to iterate through the whole list:

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

Another suggestion: You don't need the for loop to print the result, at all. Just use str.join():

print('   '.join(Names))

Upvotes: 1

Related Questions