Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Adding Items to a Tuple jn Python | Section
Python Data Structures
セクション 1.  20
single

single

bookAdding Items to a Tuple jn Python

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

To add elements to a tuple, you can use the same approach that's effective for deletion. Since tuples are immutable, you can't directly add an element to them without encountering an error. However, there are workarounds to add new elements to a tuple.

12345678910111213
# Original tuple of movies movies = ("Inception", "Interstellar", "Tenet") # Convert the tuple to a list movies_list = list(movies) # Add a new movie to the list movies_list.append("Dunkirk") # Convert the list back to a tuple movies = tuple(movies_list) print("After:", movies)
copy

Another way to add an element to a tuple is by concatenating it with another tuple. If you want to add one or more elements, simply create a new tuple with these elements and combine it with the original tuple.

12345678910
# Original tuple of movies movies = ("Inception", "Interstellar", "Tenet") # Create a new tuple with the movie to add new_movies = ("Dunkirk",) # Concatenate the tuples movies += new_movies print(movies)
copy
タスク

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

You are given the tuple animal_movies.

  • Add two new movies to this tuple: "Dumbo" and "Zootopia".
  • You can use any method to add them, either by converting to a list or by concatenating tuples.

解答

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

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

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

セクション 1.  20
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt