delete in 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: python del

# Delete Variables
my_var = 5
my_tuple = ('Sam', 25)
my_dict = {'name': 'Sam', 'age': 25}
del my_var
del my_tuple
del my_dict

# Delete item from list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# deleting the third item
del my_list[2]

# Delete from dictionary
person = { 'name': 'Sam',
  'age': 25,
  'profession': 'Programmer'
}
del person['profession']

Example 3: how to delete list python

# delete by index
a = ['a', 'b', 'c', 'd']
a.pop(0)
print(a)
['b', 'c', 'd']

Example 4: delete a value in list python

list.remove(element)

Example 5: remove value from python list by value

>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print a
['a', 'c', 'd']

Example 6: how to delete an item from a list python

myList = ['Item', 'Item', 'Delete Me!', 'Item']

del myList[2] # myList now equals ['Item', 'Item', 'Item']