I have a list
A = [A, B, #, C]
Using a.remove('#')
I can remove the hashtag, but how can I remove both the hashtag and the element before without a loop considering I don't know what the element before the hashtag is?
Use list.index
to find the position of the hashtag and then use two slices to remove the two elements.
pos = A.index('#')
A = A[:pos - 1] + A[pos + 1:]
A[:pos - 1]
gives everything up to, and not including, the element before the hashtag. A[pos + 1:]
gives everything after the hashtag, then you can combine these two into one list
Alternatively refer to @usr2564301's solution in the comments which removes it in-place (without having to reassign A): A[pos-1:pos+1] = []
, using the same pos
from above
Note : This assumes that the hashtag is not the first element in the list, otherwise unexpected behavior will occur (refer to @sertsedat's comment below)
You basically need to know the index of the hashtag.
A = ['A', 'B', '#', 'C']
hashtag_index = A.index('#')
# here I am removing the hashtag
A.pop(hashtag_index)
# here the element before
if hashtag_index != 0:
A.pop(hashtag_index - 1)
print(A)
# ['A', 'C']
You can also use del in one line (doesn't work when index == 0)
del A[hashtag_index - 1:hashtag_index+1]
If you are sure that the element is in the list, you can use index
to get the position in the list and then a couple of pop
to remove the items (assuming that if the hashtag is the first of the list, you just want to remove that):
a= ['A', 'B', '#', 'C']
index = a.index('#')
# if the element is not in the list, you will get a ValueError!
a.pop(index)
if index > 0:
a.pop(index-1)
print(a)
# output
['A', 'C']
If you are not sure that the element is in the list, you should then check first if it is, in order to avoid getting a ValueError
:
a= ['A', 'B', '#', 'C']
if '#' in a:
index = a.index('#')
a.pop(index)
if index > 0:
a.pop(index-1)
print(a)
# output
['A', 'C']
one way to do it:
A = ['A', 'B', '#', 'C']
print(A) #output = ['A', 'B', '#', 'C']
index = A.index("#")
A.pop(index)
A.pop(index-1)
print(A) #output = ['A', 'C']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.