How do I erase the elements in the list?

Asked 2 years ago, Updated 2 years ago, 138 views

I got an error when I tried to erase the missing element (Source Code 1) When erasing an element that does not exist, we created a code (source code 2) that does not cause an error. Is there an easier way than I planned?

a=[1,2,3,4]
b=a.index(6)
del a[b]
print a
Traceback (most recent call last):
  File "D:\zjm_code\a.py", line 6, in <module>
    b=a.index(6)
ValueError: list.index(x): x not in list
a=[1,2,3,4]
try:
    b=a.index(6)
    del a[b]
except:
    pass
print a

list python

2022-09-22 22:26

1 Answers

First of all, the easiest way to erase a particular element from the list is to write remove().

a = [1, 2, 3, 4, 2]
a.remove(2) #2 is not an index value but an element value
print a #[1, 3, 4, 2]

Now, moving on to your question, The code that uses remove() to ignore the error is as follows.

if c in a:
    a.remove(c)

However, remove() erases only the first element. If you want to erase all of the specific elements from the list, please write the compression in the list

a = [1, 2, 3, 4, 2, 3, 4, 2, 7, 2]
a = [x for x in a if x != 2]
print a # [1, 3, 4, 3, 4, 7]


2022-09-22 22:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.