Fopopo
0
Q:

python how to remove elements from a list

myList.remove(item) # Removes first instance of "item" from myList
myList.pop(i) # Removes and returns item at myList[i]
45
# Basic syntax:
my_list.remove(element)

# Note, .remove(element) removes the first matching element it finds in
# 	the list.

# Example usage:
animals = ['cat', 'dog', 'rabbit', 'guinea pig', 'rabbit']
animals.remove('rabbit')
print(animals)
--> ['cat', 'dog', 'guinea pig', 'rabbit'] # Note only 1st instance of
#	rabbit was removed from the list. 

# Note, if you want to remove all instances of an element, convert the
#	list to a set and back to a list, and then run .remove(element)	E.g.:
animals = list(set['cat', 'dog', 'rabbit', 'guinea pig', 'rabbit']))
animals.remove('rabbit')
print(animals)
--> ['cat', 'dog', 'guinea pig']
3
# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' is removed
animals.remove('rabbit')

# Updated animals List
print('Updated animals list: ', animals)
3
l = list[1, 2, 3, 4]

for i in range(len(list)):
  l.pop(i) # OR "l.remove(i)"
10
a = [0, 1, 2, 3, 4, 5]
el = a.pop(2)
4

New to Communities?

Join the community