Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add .discard() method. #4636

Merged
merged 16 commits into from
May 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions content/python/concepts/sets/terms/discard/discard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
---
Title: '.discard()'
Description: 'Removes a specified element from a set.'
Subjects:
- 'Computer Science'
- 'Code Foundations'
Tags:
- 'Methods'
- 'Collections'
- 'Sets'
- 'Strings'
CatalogContent:
- 'learn-python-3'
- 'paths/computer-science'
---

In Python, the **`.discard()`** method removes a specified element from a [set](https://www.codecademy.com/resources/docs/python/sets). If the element is not found, it takes no action and does not raise an [error](https://www.codecademy.com/resources/docs/python/errors) either.

## Syntax

```pseudo
set.discard(value)
```

- `set`: Refers to the set from which the specified element is to be removed.
- `value`: Denotes the element to be removed from the set.

## Example

The below example shows the usage of the `.discard()` method:

```py
coffee_set = {'espresso', 'flat_white', 'cappuccino', 'filter'}
print(coffee_set)

# Removing 'espresso' from the set
coffee_set.discard('espresso')
print(coffee_set)

# Removing 'latte' from the set
coffee_set.discard('latte')
print(coffee_set)
```

The above code produces the following output:

```shell
{'espresso', 'flat_white', 'cappuccino', 'filter'}
{'flat_white', 'cappuccino', 'filter'}
{'flat_white', 'cappuccino', 'filter'}
```

In the above example, the code continues to get executed without any errors despite the attempt to remove the element `latte`, which doesn't even exist in the set.

## Codebyte Example

Here is a codebyte example demonstrating the use of the `.discard()` method:

```codebyte/python
coffee_beans = {'Brazil', 'Ethiopia', 'Kenya', 'Columbia'}
print(coffee_beans)

coffee_beans.discard('Vietnam')
coffee_beans.discard('Brazil')
print(coffee_beans)
```
Loading