Adding Elements to Python Lists: Using append() vs. insert()

Since Python lists are mutable (changeable), you can freely add or insert elements even after creating them.

There are two basic methods for adding elements: append() and insert(). While they are similar, the difference lies in where the element is added.

This article explains the functions of append() and insert() and how to use them properly.


目次

append() – Adding an Element to the End

append() is the most commonly used method for adding elements to a list. It adds the single element passed as an argument to the end (tail) of the list.

Syntax:

list_variable.append(element_to_add)

Example:

Let’s look at an example of adding a new task to a task management list.

# List of pending tasks
pending_tasks = ["Implement User Auth", "Write Documentation"]
print(f"Before: {pending_tasks}")

# Add a new task to the end
pending_tasks.append("Write Test Code")

print(f"After:  {pending_tasks}")

Output:

Before: ['Implement User Auth', 'Write Documentation']
After:  ['Implement User Auth', 'Write Documentation', 'Write Test Code']

“Write Test Code” was added to the end of the list.


insert() – Inserting an Element at a Specific Position

insert() is used to insert a new element at a specific position (index).

Syntax:

list_variable.insert(index, element_to_insert)

The element_to_insert is placed at the specified index. The element originally at that position, and all subsequent elements, are shifted one place to the back.

Example:

Here is an example of inserting a new entry into a ranking list.

# Ranking list
user_ranking = ["Sato", "Suzuki", "Takahashi"]
print(f"Before: {user_ranking}")

# Insert "Tanaka" at index 1 (2nd place)
user_ranking.insert(1, "Tanaka")

print(f"After:  {user_ranking}")

# Insert "Watanabe" at index 0 (Top)
user_ranking.insert(0, "Watanabe")

print(f"Top Insert: {user_ranking}")

Output:

Before: ['Sato', 'Suzuki', 'Takahashi']
After:  ['Sato', 'Tanaka', 'Suzuki', 'Takahashi']
Top Insert: ['Watanabe', 'Sato', 'Tanaka', 'Suzuki', 'Takahashi']

insert(1, ...) inserted “Tanaka” between “Sato” and “Suzuki”, and insert(0, ...) inserted “Watanabe” at the very beginning of the list.


Differences Between append() and insert()

MethodLocationArgumentsNote
append()End only1 (Element)Runs fast.
insert()Any position2 (Index, Element)Can specify 0 to add to the top. May be slower for large lists (due to shifting elements).

Summary

  • Use append() when you want to add an element to the end of the list.
  • Use insert() when you want to add an element to the beginning or a specific position in the list.
  • The basic rule is: use append() for simple additions, and use insert() only when the order matters and you need to interrupt the existing sequence.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次