Dropping specific elements from lists
Question:
I have data stored in the list. Below you can see my data.
listName = ['column1','column2','column3','column4']
Now I want to drop elements with titles 'column2'
and 'column3'
I tried this command but is not work.
listName=listName.drop(['column2','column3'],axis=1)
Can anybody help me how to solve this problem?
Answers:
If you need to remove them by value, I would create a list of elements to remove and filter the former list via list-comprehension:
to_remove = ['column2','column3']
filtered = [x for x in listName if x not in to_remove]
Returning:
['column1','column4']
You can try list.remove() to drop elements from a list using the below code
listName = ['column1','column2','column3','column4']
try:
listName.remove("column1")
except ValueError:
print("Element not found!")
#Output: ['column2', 'column3', 'column4']
Handle exceptions if the element does not exist in the list
try:
listName.remove("column5")
except ValueError:
print("Element not found!")
#Output: Element not found!
I have data stored in the list. Below you can see my data.
listName = ['column1','column2','column3','column4']
Now I want to drop elements with titles 'column2'
and 'column3'
I tried this command but is not work.
listName=listName.drop(['column2','column3'],axis=1)
Can anybody help me how to solve this problem?
If you need to remove them by value, I would create a list of elements to remove and filter the former list via list-comprehension:
to_remove = ['column2','column3']
filtered = [x for x in listName if x not in to_remove]
Returning:
['column1','column4']
You can try list.remove() to drop elements from a list using the below code
listName = ['column1','column2','column3','column4']
try:
listName.remove("column1")
except ValueError:
print("Element not found!")
#Output: ['column2', 'column3', 'column4']
Handle exceptions if the element does not exist in the list
try:
listName.remove("column5")
except ValueError:
print("Element not found!")
#Output: Element not found!