Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 TypeError: list indices must be integers or slices, not str

i have the task to get the String 'AAAABBBCCDAABBB' into a list like this: ['A','B','C','D','A','B']

I am working on this for 2 hours now, and i can't get the solution. This is my code so far:

list = []

string = 'AAAABBBCCDAABBB'

i = 1

for i in string:
    list.append(i)

print(list)

for element in list:
    if list[element] == list[element-1]:
        list.remove(list[element])

print(list)

I am a newbie to programming, and the error "TypeError: list indices must be integers or slices, not str" always shows up...

I already changed the comparison

if list[element] == list[element-1]

to

if list[element] is list[element-1]

But the error stays the same. I already googled a few times, but there were always lists which didn't need the string-format, but i need it (am i right?).

Thank you for helping! NoAbL

like image 489
NoAbL Avatar asked Mar 13 '23 23:03

NoAbL


1 Answers

First of all don't name your variables after built in python statements or data structures like list, tuple or even the name of a module you import, this also applies to files. for example naming your file socket.py and importing the socket module is definitely going to lead to an error (I'll leave you to try that out by yourself)

in your code element is a string, indexes of an iterable must be numbers not strings, so you can tell python

give me the item at position 2.

but right now you're trying to say give me the item at position A and that's not even valid in English, talk-less of a programming language.

you should use the enumerate function if you want to get indexes of an iterable as you loop through it or you could just do

for i in range(len(list))

and loop through the range of the length of the list, you don't really need the elements anyway.

Here is a simpler approach to what you want to do

s = string = 'AAAABBBCCDAABBB'

ls = []

for i in s:
    if ls:
        if i != ls[-1]:
            ls.append(i)
    else:
        ls.append(i)

print(ls)
like image 98
danidee Avatar answered Mar 16 '23 05:03

danidee