-4
pasw = "1234abc"
mylist = list(pasw)
a = list(map(lambda x: mylist.remove(x) if x.isnumeric() == True else False, mylist))
print(mylist)

Output:

['2', '4', 'a', 'b', 'c']

I want to check if there is a number in the list, and if there is a number, I want to delete it from the list.

Hasan Cb
  • 37
  • 7
  • 5
    Don't modify a list while iterating over it (and for that matter, don't use `list` and `map` to do an iteration with a side effect, it's weird and confusing). Just build a new list and assign it to `mylist`: `mylist = [x for x in pasw if not x.isnumeric()]` -> `['a', 'b', 'c']`. – Samwise Nov 27 '22 at 16:33

1 Answers1

0

As a general rule, it's not recommanded to modify a sequence you are iterating upon. The below function is similar to your map.

def deleting_while_iterating(iterable):
    for i in iterable:
        iterable.remove(i)
        print(f"i: {i}, iterable: {iterable}")

If I give this function your input, the output is:

i: 1, iterable: ['2', '3', '4', 'a', 'b', 'c']
i: 3, iterable: ['2', '4', 'a', 'b', 'c']
i: a, iterable: ['2', '4', 'b', 'c']
i: c, iterable: ['2', '4', 'b']

As you can see, after the first iteration, "2" who originally was at index 1 is now at index 0. However, i is now at index 1 and thus "2" will be skipped. That's why it's better to create a new list containing only the elements you want. There are different ways to do it.

ClGide
  • 43
  • 5