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

single

bookAdding Elements to Lists in Python

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

The append() method in Python is used to add an element to the end of a list. It's a convenient way to expand a list dynamically without having to create a new one.

Imagine you have a list of cities you want to visit. You've already listed a few, but as your plans evolve, you want to add more cities without replacing the existing ones.

travel_wishlist = ["Paris", "Tokyo", "New York", "Rome"]

The list currently contains four cities. Now imagine you want to add another city, say "Sydney". Here's how you can do it:

123456
travel_wishlist = ['Paris', 'Tokyo', 'New York', 'Rome'] # Adding a new city to the travel wishlist travel_wishlist.append("Sydney") print(travel_wishlist) # Output: ['Paris', 'Tokyo', 'New York', 'Rome', 'Sydney']
copy

As you can see, "Sydney" has been added to the end of the list without affecting the existing items.

Note
Note
  • The list grows by one element every time you use append();
  • You can append not only strings but also variables, numbers, or even other lists;
  • The same logic applies to integers, floats, or any object.

The append() method allows you to efficiently update your list without recreating it. Additionally, this method is especially practical in for loops, where you can dynamically build or grow a list by adding elements iteratively based on conditions or computations.

タスク

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

You are given a list of cities, travel_wishlist.

  • Add 2 cities to the list: "Berlin", "New York".
  • Use the append method instead of recreating the list.

解答

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

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

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

セクション 1.  6
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt