How To Delete An Element From A List In Python

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeHow to delete an element from a list in Python

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)Run

del

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)Run

pop()

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)Run

Note: 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