Skip to main content
Crowdfunding
Python + AI for Geeks
Practice

Removing Elements with the del Keyword and pop() Function

To remove an element at a specific index in a list, you can use the del statement or the pop() method.


Using the del Keyword

The del statement removes the element at the specified index from the list.

Example of del Keyword
fruits = ['Apple', 'Banana', 'Cherry']

del fruits[1] # Remove the element at index 1 (second element)

print("fruits:", fruits) # ['Apple', 'Cherry']

In the code above, del fruits[1] removes the 'Banana' from the fruits list at index 1 (the second element).


Using the pop() Function

The pop() function removes the element at a specific index within parentheses (), and returns its value.

If no index is specified, it removes and returns the last element of the list.

Example of pop() Function
numbers = [1, 2, 3, 4, 5]
last_number = numbers.pop()

print("last_number:", last_number)
# 5

print("numbers:", numbers)
# [1, 2, 3, 4]

first_number = numbers.pop(0)

print("first_number:", first_number)
# 1

print("numbers:", numbers)
# [2, 3, 4]

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.