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?
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)
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
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?
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)
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