Sunday, April 20, 2025

Python Delete, Remove, Pop

To delete one element from list, again, indexes will be used:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

del names[0]
del names[0]
del names[0]

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['John']
>>> 

Actually, we can delete all of them using index 0 and for loop:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

for x in range(4):
    del names[0]

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
[]
>>> 

If we know what we are searching for, we can remove() by value:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

names.remove("Michael")
names.remove("John")

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['Samantha', 'Anastasia']
>>> 

Sometimes it's useful to target element at the end of list:


names =["Michael", "Samantha", "Anastasia", "John"]
print(names)

names.pop()
print(names)

names.pop()
print(names)

names.pop()
print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['Michael', 'Samantha', 'Anastasia']
['Michael', 'Samantha']
['Michael']
>>> 

Function pop() is useful when we need to grab that last element we removed, so we can do something more with it:


names =["Michael", "Samantha", "Anastasia", "John"]

last_element = names.pop()

print("What we pop-ed: ", last_element)
print("Names after pop:", names)

Result: 


What we pop-ed:  John
Names after pop: ['Michael', 'Samantha', 'Anastasia']
>>> 

In next tutorial, we will learn how to search for specific element, and how to use clear() function to remove all of them.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...