this is part of my code which I wrote for my project. When I run that I got an error
IndexError: list index out of range in python
s = "thisisTest"
m = list(s)
new_list = []
k = 0
d = 0
elemme = False
for i in m:
if i.islower():
elemme = True
while elemme:
k +=1
new_list[k].append(i)
elif i.isupper():
elemme = False
while elemme:
k +=1
new_list[k].append(i)
print(new_list)
Can someone explain what is a reason to that? I don't need new solution I need only explanation. Thank you for reading
new_list
starts off empty. So anything that tries to access new_list[k]
will always fail, no matter what the value of k
.
You need to append things to new_list
before you can start accessing its elements.
Additionally you can try to use new_list.append(i)
instead od new_list[k].append(i)
. Of course if new_list is list of list, then new_list[k] is correct
first of all. you must use new_list.append(i).
then I didnt understand the goal of this code. I didnt get what you re trying to do. In the code snippet:
> if i.islower():
> elemme = True
> while elemme:
> k +=1
> new_list.append(i)
you set ellemme to True and while is iterating while elemme is True (which is True always). So that will generate infinite loop and will give the memory error. On the other hand,
elemme = False
while elemme:
k +=1
new_list.append(i)
whats the need of while loop here where its obvious that elemme is false.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.