リストの値の変更と削除、取り出し等|Pythonのお勉強

リスト型の変数に入っている値の変更や削除の仕方です。

サンプルコード

# 1. Change a value in a list
v1 = [1, 2, 3, 4, 5]
v1[2] = 100
print(f"v1 is {v1}")

# 2. Change multi. values in a list
v2 = [1, 2, 3, 4, 5]
v2[1:4] = [100, 100, 100]
print(f"v2 is {v2}")

# 3. Delete a value in a list
v3 = [1, 2, 3, 4, 5]
del v3[1]
print(f"v3 is {v3}")

# 4. Delete a value that matches a given factor
v4 = [1, 2, 3, 4, 5]
v4.remove(3)
print(f"v4 is {v4}")

# 5. Delete values in a list with range
v5 = [1, 2, 3, 4, 5]
v5[1:3] = []
print(f"v5 is {v5}")

# 6. Delete all values in a list with range
v6 = [1, 2, 3, 4, 5]
v6.clear()
print(f"v6 is {v6}")

# 7. Append a value at the end of a list
v7 = [1, 2, 3, 4, 5]
v7.append(6)
print(f"v7 is {v7}")

# 8. Add a value in a specific position of a list
v8 = [1, 2, 3, 4, 5]
v8.insert(1, 100)
print(f"v8 is {v8}")

# 9. Check if a specified value in a list
v9 = [1, 2, 3, 4, 5]
v9_1 = 3 in v9
v9_2 = 100 in v9
print(f"v9_1 is {v9_1}", f"v9_2 is {v9_2}", sep="\n")

# 10. Count num. of specified value in a list
v10 = ["egg", "chicken", "onion", "egg"]
v10_find = "egg"
v10_1 = v10.count(v10_find)
print(f"v10 Number of {v10_find} in a list is {v10_1}")

# 11. Check position of a specified value in a list
v11 = ["egg", "chicken", "onion", "egg"]
v11_find = "onion"
v11_1 = v11.index(v11_find)
print(f"v11 Position of {v11_find} is {v11_1}")

# 12. Reverse order of values in a list
v12 = ["egg", "chicken", "onion", "egg"]
print(f"v12 Initial order is {v12}")
v12.reverse()
print(f"v12 The reversed order is {v12}")

# 13. Sort values to ascending
v13 = [3, 5, 2, 1, 4]
print(f"v13 List not sorted is {v13}")
v13.sort()
print(f"v13 List sorted is {v13}")

# 14. Sort values to ascending
v14 = [3, 5, 2, 1, 4]
print(f"v14 List not sorted is {v14}")
v14.sort(reverse=True)
print(f"v14 List sorted is {v14}")

# 15. Get and remove a value at the end of a list
v15 = [1, 2, 3, 4, 5]
print(f"v15 before pop() is {v15}")
v15_1 = v15.pop()
print(f"v15 Popped value is {v15_1}")
print(f"v15 after pop() is {v15}")

サンプルコード結果

>>> 
*** Remote Interpreter Reinitialized ***
v1 is [1, 2, 100, 4, 5]
v2 is [1, 100, 100, 100, 5]
v3 is [1, 3, 4, 5]
v4 is [1, 2, 4, 5]
v5 is [1, 4, 5]
v6 is []
v7 is [1, 2, 3, 4, 5, 6]
v8 is [1, 100, 2, 3, 4, 5]
v9_1 is True
v9_2 is False
v10 Number of egg in a list is 2
v11 Position of onion is 2
v12 Initial order is ['egg', 'chicken', 'onion', 'egg']
v12 The reversed order is ['egg', 'onion', 'chicken', 'egg']
v13 List not sorted is [3, 5, 2, 1, 4]
v13 List sorted is [1, 2, 3, 4, 5]
v14 List not sorted is [3, 5, 2, 1, 4]
v14 List sorted is [5, 4, 3, 2, 1]
v15 before pop() is [1, 2, 3, 4, 5]
v15 Popped value is 5
v15 after pop() is [1, 2, 3, 4]
よっさん
  • よっさん
  • 当サイトの管理人。ニューヨークの大学を飛び級で卒業。その後某日系IT企業でグローバル案件に携わる。マレーシアに1.5年赴任した経験を持つ。バイリンガルITエンジニアとしていかに楽に稼ぐか日々考えている。

コメントする

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