Thursday, September 4, 2025
HomeLanguagesPython program to remove last element from set

Python program to remove last element from set

Given a set, the task is to write a Python program to delete the last element from the set.

Example:

Input: {1,2,3,4}
Remove 4
Output: {1,2,3}

Input: {“Geeks”,”For”}
Remove Geeks
Output: {“For”}
Explanation: The idea is to remove the last element from the set 4 in the first case and “Geeks” in the second case.

Note: Sets are unordered which means any element in the set has no fixed order and it can change therefore we cannot delete any particular element with respect to its position.

Remove the last element from the set Using discard() method

discard() method can also remove the element from the set, by passing the element into this function.

Python3




s = {1, 2, 3, 4}
s.discard(4)
print(s)
 
s = {"Geeks", "For"}
s.discard("Geeks")
print(s)


Output

{1, 2, 3}
{'For'}

Remove the last element from set  Using remove()

remove() can be also used in the same ways as we see in method 1.

Python3




s = {1, 2, 3, 4}
s.remove(4)
print(s)
 
s = {"Geeks", "For"}
s.remove("Geeks")
print(s)


Output

{1, 2, 3}
{'For'}

Note: If the element is not present in the set then the remove method raises an error so if you’re not sure that the element is present or not then use the discard method.

Remove the last element from the set Using pop() 

Python3




s = {1, 2, 3, 4}
s.pop()
print(s)
 
s = {"Geeks", "For"}
s.pop()
print(s)


Output

{2, 3, 4}
{'For'}

Note: pop() method deletes random elements in the set and it raises a error if the set is empty.

Remove the last element from the set using list

In this method we first convert a set into a list then we remove the last element in that list using slicing. And in last we convert that list back to set.

Python3




s = {1, 2, 3, 4}
s = set(list(s)[:-1])
print(s)
 
s = {"Geeks", "For"}
s = set(list(s)[:-1])
print(s)


Output

{1, 2, 3}
{'Geeks'}
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6632 POSTS0 COMMENTS
Nicole Veronica
11800 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11860 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS