Python: リストの要素の追加と削除、取出し – append()、extend()、pop()、remove()メソッド

Sponsored Link

このエントリーをはてなブックマークに追加
はてなブックマーク - Python: リストの要素の追加と削除、取出し – append()、extend()、pop()、remove()メソッド
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Livedoor Clip
Bookmark this on Yahoo Bookmark

ソースコード

#!/usr/bin/python
# coding: UTF-8

# リストの要素の追加と削除(取出し) | append()、extend()、pop()、remove()メソッドの使い方

a = [3, 5, 7, 9, 11]
print a

a.append(13)               # 引数のオブジェクトをリストの末尾に追加
print a

a.extend([15, 17, 19, 21]) # 引数のシーケンスを展開して末尾に追加
print a

elm = a.pop()              # リストの末尾から要素を1つ取り出す
print 'elm == %d' % elm
print a

elm = a.pop(4)             # 引数にリストのインデックスを取り、その要素を取り出す
print 'elm == %d' % elm
print a

a.remove(13)               # 引数のオブジェクトをリスト要素から削除する
print a

実行結果

[3, 5, 7, 9, 11]
[3, 5, 7, 9, 11, 13]
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
elm == 21
[3, 5, 7, 9, 11, 13, 15, 17, 19]
elm == 11
[3, 5, 7, 9, 13, 15, 17, 19]
[3, 5, 7, 9, 15, 17, 19]

リファレンス

チュートリアル

関連すると思われる記事:

Sponsored Link

This entry was posted in Python and tagged , , . Bookmark the permalink.

Facebook comments:

コメントを残す

メールアドレスが公開されることはありません。

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>