Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python Program to Find Duplicate sets in list of sets
Next article icon

Given a set, the task is to write aPython 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 Usingdiscard() 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  Usingremove()

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'}

Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp