I have written this code
phrase="dont't panic"
plist=list(phrase)
print(plist)
l=len(plist)
print (l)
for i in range(0,9):
plist.remove(plist[i])
print(plist)
The output is
['d', 'o', 'n', 't', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c']
12
Traceback (most recent call last):
File "C:/Users/hp/Desktop/python/panic.py", line 7, in <module>
plist.remove(plist[i])
IndexError: list index out of range
why does it show:list index out of range when the length of the list is 12?
You are stepping through the list, removing characters:
Walking through the code: i=0
['o', 'n', 't', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c']
i=1
['o', 't', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c']
i=2
['o', 't', 't', ' ', 'p', 'a', 'n', 'i', 'c']
i=3
['o', 't', 't', 'p', 'a', 'n', 'i', 'c']
i=4
['o', 't', 't', 'p', 'n', 'i', 'c']
i=5
['o', 't', 't', 'p', 'n', 'c']
i=6
And now you're past the end of the array
I believe you meant to remove the first nine characters, but once you remove the first character, it's not the first character anymore. So when you remove the second character, you're actually removing the third character of the original string, so by the time you make it to i=7 or 8, there aren't enough characters left in the array anymore.
A more simple and "pythonic" way to do the same thing would be with:
plist = plist[9:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With