Programming Essentials Python - Overview of Collections - Updating and Deleting elements - list

In this article, we will explore how to update and delete elements in a list in Python. We will cover methods to update elements by index and delete elements using different functions.

Updating Elements in a List

To update elements in a list, you can simply assign a new value to the desired index in the list.

l = [1, 2, 3, 4]
l[1] = 11
print(l)

Deleting Elements from a List

There are multiple functions available in Python to delete elements from a list:

remove Function

The remove function deletes the first occurrence of the specified element from the list.

l = [1, 2, 3, 4, 4, 6]
l.remove(4)
print(l)

pop Function

The pop function deletes the element at the specified index from the list.

l = [1, 2, 3, 4, 4, 6]
l.pop()
print(l)

l.pop(2)
print(l)

clear Function

The clear function deletes all the elements from the list, making it empty.

l = [1, 2, 3, 4, 4, 6]
l.clear()
print(l)

Hands-On Tasks

  1. Update the second element in a list with a new value.
  2. Remove a specific element from a list.
  3. Pop an element from the list at a given index.
  4. Clear all the elements from a list.

Conclusion

In this article, we have learned how to update and delete elements in a list in Python. By practicing the hands-on tasks provided, you can solidify your understanding of these concepts. Remember to engage with the community for further learning and support.

Watch the video tutorial here