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.
Asked
Active
Viewed 1,242 times
-1
-
2Just .. assign the index the desired value. – user2864740 Jan 24 '14 at 08:05
2 Answers
2
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 1
s 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]

thefourtheye
- 233,700
- 52
- 457
- 497
-
2Note 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). – Jonas Schäfer Jan 24 '14 at 08:08
-
Inplace replacement is worth the extra resources only when the list **A** is referenced by another objects – volcano Jan 24 '14 at 08:28
1
If you only know the value, this will replace the first occurrence:
A[A.index(1)] = None
If you know the index:
A[6] = None

Steinar Lima
- 7,644
- 2
- 39
- 40