-1

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.

1
  • 2
    Just .. assign the index the desired value. Commented Jan 24, 2014 at 8:05

2 Answers 2

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 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]
Sign up to request clarification or add additional context in comments.

2 Comments

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).
Inplace replacement is worth the extra resources only when the list A is referenced by another objects
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.