セクション 1. 章 25
single
Removing Items from Sets in Python
メニューを表示するにはスワイプしてください
Sets in Python allow you to remove elements using the remove() and discard() methods. While both methods remove specific elements, there is a key difference:
remove(): raises aKeyErrorif the element is not in the set;discard(): does not raise an error if the element is not found; it simply leaves the set unchanged.
123456# Attempting to remove movies movies = {"Inception", "Interstellar", "Tenet", "Dunkirk"} # Remove specific movies movies.remove("Dunkirk") movies.remove("Avatar") # This will raise a `KeyError`
Now, let's use the discard() method, which behaves similarly but avoids errors if the specified movie is not in the set.
12345678910# Define a set of favorite movies movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"} # Remove specific movies using discard movies.discard("Dunkirk") movies.discard("Memento") movies.discard("Avatar") # Print the result print("Final set:", movies)
タスク
スワイプしてコーディングを開始
You are given the set marvel_movies. However, two movies from another studio have accidentally been added to this set.
- Remove the movie
"The Dark Knight"from the set. - Remove the movie
"Justice League"from the set. - Use the
discard()orremove()methods to accomplish this task.
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 25
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください