'Getting "IndexError: list index out of range" when trying to append to nested list

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.



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel Roseman
Solution 2 Manpreet Ahluwalia