Issue
While running the following code
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
# write your for loop here
for index in range(len(names)):
usernames[index] = names[index].lower().replace(" ", "_")
print(usernames)
this error is observed
Traceback (most recent call last):
File "vm_main3.py", line 47, in <module>
import main
File "/tmp/vmuser_kncqjadnfl/main.py", line 2, in <module>
import studentMain
File "/tmp/vmuser_kncqjadnfl/studentMain.py", line 1, in <module>
import usernames
File "/tmp/vmuser_kncqjadnfl/usernames.py", line 6, in <module>
usernames[index] = names[index].lower().replace(" ", "_")
IndexError: list assignment index out of range
any help will be appreciated.
Solution
Most errors speak for themselves.
Your list usernames
is initialized as empty, that is, of length 0. So whatever integer index
is, usernames[index]
will try to access a nonexistent element. That's why you get an IndexError
.
What you want to do is to append elements to a list usernames
. append
method does that. So your for-loop should read:
for index in range(len(names)):
usernames.append(names[index].lower().replace(" ", "_"))
Try reading any python-beginner's tutorial about lists, or at least the official documentation before proceeding.
Answered By - Ignatius
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.