delete an element of a list in python in python

To delete an element from a list in Python, you can use the del keyword or the remove() method.

Here is an example using the del keyword:

main.py
my_list = [1, 2, 3, 4, 5]

# Deleting element at index 2
del my_list[2]

print(my_list)  # [1, 2, 4, 5]
104 chars
7 lines

And here is an example using the remove() method:

main.py
my_list = [1, 2, 3, 4, 5]

# Removing the element 3
my_list.remove(3)

print(my_list)  # [1, 2, 4, 5]
102 chars
7 lines

Both methods allow you to delete elements from a list in Python. The del keyword is used when you know the index of the element you want to delete, while the remove() method is used when you know the value of the element you want to remove.

related categories

gistlibby LogSnag