22
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonのリスト連結方法,list.extend()と “+” 演算子の違い

Last updated at Posted at 2015-09-21

Pythonリストの連結方法

とても初歩的なことですが
pythonのリスト連結でハマったのでまとめておきます.

連結方法は2通り.

  1. list.extend()メソッドを使う
  2. リストオブジェクトを + 演算子で連結
listSample.py

hoge = ["1", "2"]
foo  = ["3", "4"]

# やりがちなNG: hoge.extend(foo)の返り値はNone.したがって NoneType has no len.
while len(hoge) < 10:
    hoge = hoge.extend(foo)

# OK
while len(hoge) < 10:
    hoge = hoge + foo

# OK
while len(hoge) < 10:
    hoge.extend(foo)

参考文献

のんびりPython リスト追加についての速度比較(append,内包表記など)

22
15
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
22
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?