Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Tuple Methods | Other Data Types
Introduction to Python
セクション 4.  6
single

single

bookTuple Methods

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

Tuple Methods

While tuples do not support methods that alter their content, they still provide a few built-in methods to help manage and utilize them effectively. Here are the two built-in methods you can use with tuples:

  • count(): returns the number of times a specified value appears in the tuple;
  • index(): searches the tuple for a specified value and returns the index position of where it was first found.
Note
Note

The same methods can also be used with lists.

12345678910
# Example tuple containing a mix of integers and strings fruits = ("apple", "banana", "cherry", "apple", "banana", "cherry", "apple") # Use the `count()` method to determine how many times "apple" appears in the tuple apple_count = fruits.count("apple") print("Number of times 'apple' appears:", apple_count) # Use the `index()` method to find the first occurrence of "cherry" in the tuple cherry_index = fruits.index("cherry") print("The first occurrence of 'cherry' is at index:", cherry_index)
copy

Let's look on another example, that demonstrates how to use tuple methods on the hands on tasks.

12345678910
# Tuple containing store departments store_departments = ("Produce", "Deli", "Bakery", "Produce", "Seafood", "Deli", "Produce") # Use count() to find how many times "Produce" appears produce_count = store_departments.count("Produce") print("'Produce' appears:", produce_count) # Use index() to find the first index of "Seafood" seafood_index = store_departments.index("Seafood") print("The first occurrence of 'Seafood' is at index:", seafood_index)
copy
タスク

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

You are helping to analyze a grocery store's department organization!

  • Use the provided grocery_departments tuple, which lists the departments in the order they appear in the store.
  • Assign to produce_count the number of times the 'Produce' department appears in the tuple using a tuple method.
  • Assign to first_bakery_index the index of the first occurrence of the 'Bakery' department using a tuple method.
  • Do not change the grocery_departments tuple.

Complete the code by filling in the two variables using the appropriate tuple methods.

解答

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

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

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

セクション 4.  6
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt