Python provides many ways to remove items from a list. Let's understand remove()
, pop()
, del
, and clear()
with examples.
Python में list से item हटाने के कई तरीके हैं। आइए remove()
, pop()
, del
और clear()
को उदाहरण के साथ समझें।
students = ["Raj", "Simran", "Aman"]
students.remove("Simran")
print(students)
Output:
["Raj", "Aman"]
students = ["Raj", "Simran", "Aman"]
students.pop()
print(students)
Output:
["Raj", "Simran"]
students = ["Raj", "Simran", "Aman"]
students.pop(0)
print(students)
Output:
["Simran", "Aman"]
students = ["Raj", "Simran", "Aman"]
del students[1]
print(students)
Output:
["Raj", "Aman"]
students = ["Raj", "Simran", "Aman"]
del students
# Now students no longer exists
Output:
NameError: name 'students' is not defined
students = ["Raj", "Simran"]
students.clear()
print(students)
Output:
[]
students = ["Raj", "Simran", "Aman"]
to_remove = input("Enter name to remove: ")
if to_remove in students:
students.remove(to_remove)
else:
print("Name not in list")
print(students)
Output:
Enter name to remove: Simran ['Raj', 'Aman']