3

I have an object 'a' I want to convert it to a list such that it does not have any characters but numbers. Though, similar questions talk about list comprehensions but i was looking for a function method which will help me collect the numbers.

>>> a
['(', '0', ',', ' ', '1', ',', ' ', '2', ',', ' ', '3', ',', ' ', '4', ',', ' ', '5', ',', ' ', '6', ',', ' ', '7', ',', ' ', '8', ',', ' ', '9', ')']

Now, I was thinking about approaching this problem in two parts. First, i wanted to remove all ',' and ' '(blank spaces).

For this I coded :

>>> for x in a :
    if x == ',' or x == ' ':
        del x

This does not change the list at all.

Also, is there any way in which I can iterate through each object and check if it is a number and if it is not delete it. I think this would be much simpler.

Moreover, if there is a better way to resolve this, please suggest.

  • Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Sayse May 07 '19 at 09:39
  • The `del` statement can't delete things that a variable is pointing to since it only deletes the first level reference. https://docs.python.org/3/reference/simple_stmts.html#the-del-statement "Deletion of a name removes the binding of that name from the local or global namespace" So all you're doing with `del x` is remove the binding for `x` - and not the thing that `x` is pointing to. – rdas May 07 '19 at 09:42

1 Answers1

8

As a general rule you should avoid modifying an iterable while iterating over it (see why), although in this case your code is not deleting any elements as @rdas points out. Use a list comprehension instead:

[i for i in l if i.isnumeric()]
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
yatu
  • 80,714
  • 11
  • 64
  • 111
  • 1
    This was so simple. Thanks a lot. – Vinamra Bali May 07 '19 at 09:41
  • 1
    @VinamraBali you're welcome! Don't forget you can upvote/accept, see [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – yatu May 07 '19 at 09:45
  • 2
    Yes, but don't forget to accept :), see the link I shared (green tick under the voting options) @VinamraBali – yatu May 07 '19 at 09:59
  • 1
    Make sure `isnumeric` test is consistent with your notion of a 'number' string. E.g. these are NOT numeric: "+1", "-1", "0.0". – VPfB May 07 '19 at 10:15