Let suppose I have a list A = [None, None, None, None, None, None, 1, 2, 3, 4]. As of now the size of the list is 10. Now I want to delete a specific element say 1 but at the same time I want that 1 should be replace by None and the size of the list is retained. Deleting 1 should not change the size of the list to 9.
-
2Just .. assign the index the desired value.user2864740– user28647402014-01-24 08:05:47 +00:00Commented Jan 24, 2014 at 8:05
Add a comment
|
2 Answers
If you want to remove only the first element, you can do this
A[A.index(1)] = None
But, if you want to replace all the 1s in the list, you can use this list comprehenesion
A = [None if item == 1 else item for item in A]
If you want to do inplace replacement, you can do it like this (thanks to @Jonas)
A[:] = [None if item == 1 else item for item in A]
You can write generic functions, like this
A, B = [None,None, None, None, None, None, 1, 1, 3, 4], [1, 1, 1]
def replace(input_list, element, replacement):
try:
input_list[input_list.index(element)] = None
except ValueError, e:
pass
return input_list
def replace_all(input_list, element, replacement):
input_list[:] = [replacement if item == element else item for item in input_list]
return input_list
print replace(A, 1, None)
print replace_all(B, 1, None)
Output
[None, None, None, None, None, None, None, 1, 3, 4]
[None, None, None]
2 Comments
Jonas Schäfer
Note that the second statement is not in place, in contrast to the first (and the usual
del operator which does not apply to this question). To make the second statement in place, you have to change the left-hand-side to A[:] (just sayin’, might cause confusion).volcano
Inplace replacement is worth the extra resources only when the list A is referenced by another objects