0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのlist.append()とlist.extend()の違い

Posted at

Pythonでリストに要素を追加する方法として、append()extend()があります。本記事では、それぞれの違いについて詳しく解説します。

append()メソッド

append()はリストの末尾に1つの要素を追加するメソッドです。このメソッドはリスト自体を変更しますが、返り値はNone なので注意が必要です。

使用例

a = [1, 2, 3]
print(a)  # [1, 2, 3]

b = a.append(4)  # `append()` は `None` を返す
print(a)  # [1, 2, 3, 4]
print(b)  # None

append()を使うとリストa自体が変更されるため、新しい変数bにはNoneが入ります。

extend()メソッド

extend()はリストに 別のiterable(イテラブル) の要素を追加するメソッドです。こちらもリスト自体を変更し、返り値はNone です。

extend()の引数に関する注意点

extend()の引数はiterable(イテラブル) である必要があります。iterableとは、forループなどで要素を1つずつ取り出せるオブジェクトのことです。例えば、listtuplestrなどが該当します。

使用例

x = [1, 2, 3]
print(x)  # [1, 2, 3]

# x.extend(4)  # TypeError: 'int' object is not iterable

y = x.extend([4])  # `extend()` は `None` を返す
print(x)  # [1, 2, 3, 4]
print(y)  # None

extend()の引数には リストのようなiterable を渡す必要があり、整数を渡すとエラーになります。

(番外編)新しい変数に反映したい場合

append()extend()はリストを直接変更するため、新しい変数に代入してもNoneが入ります。新しい変数に変更後のリストを代入したい場合は、+ 演算子を使います。

使用例

s = [1, 2, 3]
print(s)  # [1, 2, 3]

t = s + [4]  # `s` は変更されず、新しいリストが `t` に代入される
print(s)  # [1, 2, 3]
print(t)  # [1, 2, 3, 4]

+ を使うと元のリストsを変更せずに、新しいリストを作成できます。

まとめ

メソッド 動作 返り値
append(x) リストの末尾に x を追加 None
extend(iterable) リストの末尾に iterable の要素を追加 None
+ 新しいリストを作成 新しいリスト
  • append() は1つの要素を追加するが、返り値はNone
  • extend() はiterableの要素を展開して追加するが、返り値はNone
  • 新しいリストとして扱いたい場合は + を使う。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?