LukasMetlicka
LukasMetlicka

Reputation: 39

Python3.4 for loop iteration issues

I've been working on a project where I iterate through a list of data and remove all of the text before certain characters. (here's an example for reference)

>>> myList = ['foo<foo','bar<bar','baz<baz']
>>> for element in myList:
    for char in element:
        if (char == "<"):
            break
        else:
            charIndex = element.index(char)
            elementIndex = myList.index(element)
            print(charIndex, elementIndex)
            myList[elementIndex] = element[charIndex + 1 :]
0 0
Traceback (most recent call last):
  File "<pyshell#37>", line 7, in <module>
    elementIndex = myList.index(element)
ValueError: 'foo<foo' is not in list
>>> myList
['oo<foo', 'bar<bar', 'baz<baz']
>>> 

for reasons unknown to me, the element isn't renamed after it has been reassigned.
Any help would be great, thanks in advance!

Upvotes: 1

Views: 69

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You are removing the first character when setting myList[elementIndex]=

['oo<foo', 'bar<bar', 'baz<baz']

myList[elementIndex] = element[charIndex + 1:] # removes f

element[charIndex + 1:]  is from the `first index + 1` so it becomes `'oo<foo'`

If you put a print(element[charIndex + 1 :]) in your loop you will see 'oo<foo' so 'foo<foo' will not be in your myList anymore and you will get the ValueError

You have assigned element to 'foo<foo' on the first iteration in for element in myList so you are comparing to the original element not the updated list element in the second loop.

You need to update the value of element in the second loop:

 myList[elementIndex] = element[charIndex + 1 :]
 element = element[charIndex + 1 :]

Which outputs:

['<foo', '<bar', '<baz']

You can also do this in one line with a list comp, this will also work if "<" is not in some of the strings:

[s[s.index("<"):] if "<" in s else s for s in myList ]

Upvotes: 1

Related Questions