Pythonのリスト型操作いろいろ

Pythonの認定基礎試験合格に向けて勉強していますが、個人的なメモを投稿していこうと思います。

体裁は気にせず記載するため、読みにくいかも知れませんが、同じく勉強をしている方のお役に少しでも立てれば良いと思います。

リストの結合(新しいリストを用意)

リストは結合ができます。新しいリストを定義して結合する方法です。

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2

print(list1)
print(list2)
print(list3)

# Output Result
# [1, 2, 3]
# [4, 5, 6]
# [1, 2, 3, 4, 5, 6]

リストの結合(リストの拡張)

定義済みのリストを拡張する方法です。方法は2通りあります(私の知る限りでは)。

list_A = [1, 2, 3]
list_B = [4, 5, 6]
list_A += list_B

print(list_A)
print(list_B)

# Output Result
# [1, 2, 3, 4, 5, 6]
# [4, 5, 6]

もう一つは.extend()を使う方法です。

list_A = [1, 2, 3]
list_B = [4, 5, 6]
list_A.extend(list_B)

print(list_A)
print(list_B)

# Output Result
# [1, 2, 3, 4, 5, 6]
# [4, 5, 6]

どちらも結果は変わりませんが、前者の方が初心者にも分かりやすい気がしました。一方で、Pythonの強みでもあるメソッドの利用は、やはり、Pythonを勉強していく上で通るべき道だと思うので、私はなるべく後者を使っていきたいなと思います。

リストの値の削除、挿入、並び替え等

リストの色々な操作です。

# Define a list
list = ["Apple", "Banana", "Chocolate", "Doughnut", "Egg"]

# Delete a value
del list[0]
print(list)

# Insert a value
list.insert(0, "Apple")
print(list)

# Sort values in a list
list.sort(reverse=True)
print(list)

リストに対してdelは削除だが、popは削除して取り出せる

リスト内のとある値を消す方法がいくつかありますが、delとpop()の違いは、削除した値を取り出せるかです。

list = [1, 2, 3, 4, 5, 6]

del list[len(list)-1]
print(list)

list2 = [1, 2, 3, 4, 5, 6]
right = list2.pop()
print(list)
print(right)

# Output Result
# [1, 2, 3, 4, 5]
# [1, 2, 3, 4, 5]
# 6

リストの値を範囲指定で削除

リストにはスライシングという技が使えます。指定したインデックス番号の値を操作することができます。

以下のコードは、とあるリストの2番目から4番目の値を削除しています。list[1:4]はインデックス指定です。

list = [1, 2, 3, 4, 5]
list[1:4] = []
print(list)

# Output Result
# [1, 5]

リスト内に特定の値が何個あるか調べる

リストの値は重複が許されますが、指定した値が何個あるか調べることができます。その際は.count()を使用します。

list = ["Apple", "Banana", "Chocolate", "Doughnut", "Egg", "Apple", "Banana", "Zoo"]
count = list.count("Apple")
print(f"How many apples?", f"There are {count} apples.", sep="\n")

# Output Result
# How many apples?
# There are 2 apples.

特定の値のインデックス番号を取得する

値を指定して、そのインデックス番号を得ることができます。

list = ["Apple", "Banana", "Chocolate", "Doughnut", "Egg", "Apple", "Banana", "Zoo"]
index = list.index("Chocolate")
print(f"Index is", index, "so...")
print(f"Chocolate is ", index + 1, "st/nd/rd/th value.")

# Output Result
# Index is 2 so...
# Chocolate is  3 st/nd/rd/th value.
よっさん
  • よっさん
  • 当サイトの管理人。ニューヨークの大学を飛び級で卒業。その後某日系IT企業でグローバル案件に携わる。マレーシアに1.5年赴任した経験を持つ。バイリンガルITエンジニアとしていかに楽に稼ぐか日々考えている。

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です