delete python code example

Example 1: python delete file

import os
import shutil

if os.path.exists("demofile.txt"):
  os.remove("demofile.txt") # one file at a time

os.rmdir("test_directory") # removes empty directory
shutil.rmtree("test_directory") # removes not empty directory and its content

Example 2: remove object from array python

my_list = [1,2,4,6,7]

del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list

Example 3: 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 4: 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 5: delete a value in list python

list.remove(element)

Example 6: remove value from python list by value

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