Pythonでの配列(リスト)の基本操作について解説していきます。
Pythonの実行環境がない人は、環境構築をしなくても
実行できるので、こちらを参考にして下さい。

プログラミングを始めたい人向けに、Pythonの使い方を解説 ~ Colaboratory ~
この記事ではプログラミングを始めてみたい方への解説をしていきます。
突然ですが、皆さんは環境構築が不要でPythonが実行できることを知っていますか?
colaboratoryを使えば、初心者でもサクッとPythonを学ぶことが出来ちゃうんです!
配列の作成
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
要素の追加
末尾に挿入 (append)
list.append(x)
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # wordの末尾に追加 word.append("b") print(word)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘b’]
指定位置に挿入 (insert)
list.insert(i , x)
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # 3番目の次に挿入 word.insert(3, "b") print(word)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
[‘a’, ‘b’, ‘c’, ‘b’, ‘d’, ‘e’]
要素の削除
インデックスを指定して削除 (del)
del list[i] 又は del list[i : j]
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # wordの0番目を削除 del word[0] print(word) # wordの1番目から3-1番目の範囲を削除 del word[1:3] print(word)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
[‘b’, ‘c’, ‘d’, ‘e’]
[‘b’, ‘e’]
値を指定して削除 (remove)
list.remove(x)
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # word内の"b"を削除 word.remove("b") print(word)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
[‘a’, ‘c’, ‘d’, ‘e’]
すべて削除 (clear)
list.clear()
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # wordの要素をすべて削除 word.clear() print(word)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
[]
del list[:] でも同様の処理ができます。
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # wordの要素をすべて削除 del word[:] print(word)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
[]
要素のカウント (count)
list.count(x)
#「a,b,c,d,e,b」を持った配列を作成 word = ["a", "b", "c", "d", "e","b"] # 配列wordを表示 print(word) # word内の"b"をカウント print(word.count("b"))
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘b’]
2
要素の反転 (reverse)
list.reverse()
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # 配列内の順序を反転 word.reverse() print(word)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
[‘e’, ‘d’, ‘c’, ‘b’, ‘a’]
配列の長さを取得 (len)
len(list)
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # 配列wordの長さを表示 print(len(word))
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
5
配列のコピー (copy)
list.copy()
#「a,b,c,d,e」を持った配列を作成 word = ["a", "b", "c", "d", "e"] # 配列wordを表示 print(word) # wordをword2にコピー word2 = word.copy() print(word2)
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
最後に
いかがだったでしょうか。
今回はPythonの配列について解説しました。
Pythonには様々なメソッドが用意されているので、少しずつ使い方を学んでいきましょう!
コメント