VALUE ERROR IN LIST
Understand Value Error at list.
code:
def mylist_errors(tmp_lst):
# need to search for value 100 in the list.
val_search = 100
for x_lst in tmp_lst:
if x_lst is x_lst:
tmp_lst.remove(val_search)
else:
tmp_lst.append(val_search)
print(tmp_lst)
if __name__ == '__main__':
temp_list = [0, 200, 'apple', 900, 'orange']
mylist_errors(temp_list)
system out:
tmp_lst.remove(val_search)
ValueError: list.remove(x): x not in list
Errors on way while code:
From above code, list don't have val_search = 100 , so if you try to check the un-listed value from existing list, will throw following ValueError.
if x_lst is x_lst:
tmp_lst.remove(val_search)
How to Mitigate this situation:
Before performing operation on list, evaluate the variable/value is available in list.
Code:
def mylist_errors(tmp_lst):
# need to search for value 100 in the list.
val_search = 100
if val_search in tmp_lst:
print(True)
else:
print(False)
Next Method is to use Try Except block
try:
if val_search in tmp_lst:
print('working')
except ValueError:
print('Error')
Comments
Post a Comment