0

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?

joeqesi
  • 99
  • 8
  • What do you want to achieve with `i for i in test`? – NoDataDumpNoContribution Jul 03 '14 at 14:06
  • Why don't you simply: `''.join([x for x in str if not x.isdigit()])`? This removes the digits from the string. Do this for all elements in your list. – Maroun Jul 03 '14 at 14:08
  • 1
    The expectation was that [i for i in test] would replace the original values with the new values, although seeing as it hasn't worked, I should have probably removed it. – joeqesi Jul 03 '14 at 14:08
  • @user3801997 You should use different variable names to not fall into the trap of shadowing `i for i in whatever` in Python does nothing at all. Also there are much simpler solutions to your problem. See the answers. :) – NoDataDumpNoContribution Jul 03 '14 at 14:12
  • Maroun Maroun, I just tried using your code, and whilst it is neater, I still have the same problem. – joeqesi Jul 03 '14 at 14:12

2 Answers2

2

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)
Matthew Franglen
  • 4,441
  • 22
  • 32
0
    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
The2ndSon
  • 307
  • 2
  • 7