Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Machine Learning by (47.6k points)

a = [1, 2, 3, 4]

b = a.index(6)

del a[b]

print a

The above shows the following error:

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

So I have to do this:

a = [1, 2, 3, 4] 

try: 

   b = a.index(6) 

   del a[b] 

except: 

   pass 

print a

But is there not a simpler way to do this?

1 Answer

0 votes
by (106k points)

To remove the first occurrence of an element by value in a list, you can simply use list.remove():-

x = ['a', 'b', 'c', 'd', ‘b’] 

x.remove('b')

print (x )

image

To remove all the occurrences of an element in a list you can use a list comprehension:-

y = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]

y = [i for i in y if i != 20]

print (y)

image

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.6k points)

Browse Categories

...