How To Delete An Element From A List In Python
Có thể bạn quan tâm
When working with lists, one often needs to remove certain elements from them permanently. Luckily, Python provides many different yet simple methods to remove an element from a list.
remove()
remove() deletes the first instance of a value in a list. This method should be used when one knows exactly which value they want to delete regardless of the index. The code below demonstrates this:
l = [1, 4, 6, 2, 6, 1]print("List before calling remove function:")print(l)l.remove(6)print("List after calling remove function:")print(l)Rundel
del can be used to delete a single index of a list, a slice of a list, or the complete list. For this shot, let’s look at how we can delete a value at a certain index with the del keyword:
l = [1, 4, 6, 2, 6, 1]print("List before calling del:")print(l)del l[3]print("List after calling del:")print(l)Runpop()
The pop method removes an element at a given index and returns its value. The code below shows an example of this:
l = [1, 4, 6, 2, 6, 1]print("List before calling pop function:")print(l)print(l.pop(4))print("List after calling pop function:")print(l)RunNote: The argument passed to the pop method is optional. If not passed, the default index (-1) is passed as an argument so the last element in the list is removed.
Relevant Answers
Explore Courses
Free Resources
License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)Từ khóa » Xóa Python
-
Cách để Gỡ Cài đặt Python - WikiHow
-
Hướng Dẫn Chi Tiết Cách để Gỡ Cài đặt Python - Sotay.Mobi
-
Python Delete File - W3Schools
-
Xóa Biến Trong Python
-
How To Delete Python From Visual Studio - Microsoft Q&A
-
Xóa Python Trong Ubuntu, Mất Terminal, Mất Hết File - Dạy Nhau Học
-
Python - How To Delete The Contents Of A Folder? - Stack Overflow
-
Python Delete Directory - Linux Hint
-
How To Delete A Property From An Object In Python
-
How To Remove A Key From A Python Dictionary – Delete Key From Dict
-
Delete Selection Of Variables With Python - SPSS Tutorials
-
How To Delete A File In Python Article
-
Delete An Account – Python - Stripe API Reference
-
Delete Command - Autodesk