remove list of elements from list python code example

Example 1: python remove element from list

myList.remove(item) # Removes first instance of "item" from myList
myList.pop(i) # Removes and returns item at myList[i]

Example 2: delete all list entries in a range python

L2 = [ x for x in L1 if -1 <= x <= 1 ]

Example 3: remove element from list python

# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']

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

# Updated animals List
print('Updated animals list: ', animals)

Example 4: python list remove item by value

l = ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave']
print(l)
# ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave']

l.remove('Alice')
print(l)
# ['Bob', 'Charlie', 'Bob', 'Dave']

Example 5: remove one value from list more than once

# list with integer elements
list = [10, 20, 10, 30, 10, 40, 10, 50]
# number (n) to be removed
n = 10

# print original list 
print ("Original list:")
print (list)

# loop to traverse each element in list
# and, remove elements 
# which are equals to n
i=0 #loop counter
length = len(list)  #list length 
while(i<length):
	if(list[i]==n):
		list.remove (list[i])
		# as an element is removed	
		# so decrease the length by 1	
		length = length -1  
		# run loop again to check element							
		# at same index, when item removed 
		# next item will shift to the left 
		continue
	i = i+1

# print list after removing given element
print ("list after removing elements:")
print (list)

Tags:

Misc Example