セクション 1. 章 20
single
Adding 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)
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)
タスク
スワイプしてコーディングを開始
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.
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 20
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください