Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Deleting Specific Elements from Lists in Python | Section
Python Data Structures
セクション 1.  9
single

single

bookDeleting Specific Elements from Lists in Python

メニューを表示するにはスワイプしてください

The remove() method deletes the first occurrence of a specific value in the list. This is particularly useful when you know the element's value but not its index. The syntax of remove() method is:

list.remove(value)

Now, you decide to remove "Kyoto" from your list because you've already visited it. Here's how you can do it:

12345
travel_wishlist = ["Paris", "Oslo", "Kyoto", "Sydney"] # Remove a specific city travel_wishlist.remove("Kyoto") print(travel_wishlist) # Output: ['Paris', 'Oslo', 'Sydney']
copy

If "Kyoto" isn't on the list, this code will raise an error.

12345
travel_wishlist = ["Paris", "Oslo", "Rome", "Sydney"] # Remove a specific city travel_wishlist.remove("Kyoto") print(travel_wishlist) # ValueError: list.remove(x): x not in list
copy

To avoid this, you can check if the city exists before removing it:

123456
travel_wishlist = ["Paris", "Oslo", "Rome", "Sydney"] if "Kyoto" in travel_wishlist: travel_wishlist.remove("Kyoto") print(travel_wishlist)
copy
Note
Note

With the remove() method, you can only take out one item at a time.

タスク

スワイプしてコーディングを開始

You are continuing to work with the travel_wishlist list.

  • Remove the elements "Oslo" and "Sydney" from the list.
  • Use the remove() method to remove these elements.

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  9
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt