Lecture
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]
Previous lessonComparing List Concatenation and Element Addition in PythonNext lessonRemoving an Element with a Specific Value using remove() Function
Lessons in this chapter · List and Tuple data types for storing data in sequence
- 1. How to Store Ordered Data List
- 2. How to Utilize Values in a List
- 3. List IndexError Exception Handling
- 4. How to Concatenate, Repeat, and Determine the Length of Lists
- 5. Adding Elements with append() and insert()
- 6. Multiple-choice quiz
- 7. Comparing List Concatenation and Element Addition in Python
- 8. Removing Elements with the del Keyword and pop() Function
- 9. Removing an Element with a Specific Value using remove() Function
- 10. Using the clear() Function to Remove All Values in a List
- 11. Sorting List Elements with the sort() Function
- 12. How to Check if a List Contains a Specific Element
- 13. Multiple-choice quiz
- 14. Immutable Data Type, Tuple
- 15. Immutability of Tuples and Exception Handling
- 16. Accessing Specific Elements with Tuple Indexing
- 17. Selecting a Portion of a Tuple with Slicing
- 18. How to Perform Operations on Tuples
- 19. Coding Quiz - Sorting Lists
- 20. Multiple-choice quiz
- 21. Fill-in-the-blank quiz
Quiz
0 / 1
Remove Element with pop()
How do you remove 'apple' using the pop() function from the list below?
Expected output: removed: apple
fruits = ['apple', 'banana', 'cherry']removed = fruits.popprint('removed:', removed)Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help