Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python :for loop list not counting space and " ,"

Tags:

python

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?

like image 794
Debashree Bardhan Avatar asked Dec 04 '25 14:12

Debashree Bardhan


1 Answers

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:]
like image 193
Stack Tracer Avatar answered Dec 07 '25 04:12

Stack Tracer