Python program to remove last element from set

• Last Updated : 07 Nov, 2022

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.

Method 1: 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'}
```

Method 2: 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.

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.

Method 4: 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'}```

My Personal Notes arrow_drop_up