For loop doesn't change the variable being operated on

Question:

I’m trying to write part of a program that takes in a previously generated list where all the items in the list are strings containing both letters and numbers, and removes all the letters.

This is the code I’ve written to do that:

test = ["test252k", "test253k"]
numbers = list(str(range(0,10)))

for i in test:
    i = list(i)
    i = [x for x in i if x in numbers]
    i = "".join(str(e) for e in i)
    test = [i for i in test]

But when I print test, I just get the original list from line 1.

What do I do to ensure that the for loop replaces the original values for i with the new values?

Asked By: joeqesi

||

Answers:

Your real problem is that you do not update test in any way. When you perform the [i for i in test] list comprehension your use of i shadows the variable declared in the outer loop. If i has the updated value then just append it to a new list:

new_list = []
for i in test:
    i = list(i)
    i = [x for x in i if x in numbers]
    i = "".join(str(e) for e in i)
    new_list.append(i)
Answered By: Matthew Franglen
    test = ["test252k", "test253k"]
    numbers = list(str(range(0,10)))
    count = 0
    for i in test:
        i = list(i)
        i = [x for x in i if x in numbers]
        i = "".join(str(e) for e in i)
        test[count] = i
        count = count + 1

    print test
Answered By: The2ndSon
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.