【Python入門】リスト(配列)から要素をポップする/取り出す/抜き出す方法とは?リスト(配列)の要素のポップ/取り出し/抜き出し方法を徹底解説

Python

Pythonのリスト(配列)とは、複数の要素を格納できるデータ型の1つで、要素の順序を保持します。リストは角かっこ [] で囲まれ、カンマ , で区切られた複数の要素を含むことができます。リストの要素には、異なるデータ型のオブジェクトを含むことができます。また、リストは可変(mutable)オブジェクトであり、要素を追加、削除、更新することができます。本記事では、Pythonによるリスト(配列)から要素をポップする/取り出す/抜き出す方法を紹介します。

下記の様な内容で悩んでいる/困っている場合に使える方法を参考までにご共有させて頂きます。

・Pythonの場合、どうやって配列から要素を取り出すの?
・Pythonのリスト(配列)は、どの様にリスト(配列)から取り出すのだろうか?

リスト(配列)の要素のポップ/取り出し/抜き出し(自作関数)

関数の定義

def popElementFromList(input_list:list, input_id:int=-1) -> list:
    if not (-len(input_list) <= input_id <= len(input_list)-1): return (None, input_list)
    temp_list = input_list.copy()
    pop_value = temp_list.pop(input_id)
    return (pop_value, temp_list)

使用例1

SampleList = [1,2,3]
PoppedValue, NewList = popElementFromList(SampleList)
print(f"Popped Value:\n{PoppedValue} {type(PoppedValue)}")
print(f"New List:\n{NewList} {type(NewList)}")
Popped Value:
3 <class 'int'>
New List:
[1, 2] <class 'list'>

使用例2

SampleList = [1,2,3]
PoppedValue, NewList = popElementFromList(SampleList, 1)
print(f"Popped Value:\n{PoppedValue} {type(PoppedValue)}")
print(f"New List:\n{NewList} {type(NewList)}")
Popped Value:
2 <class 'int'>
New List:
[1, 3] <class 'list'>

使用例3

SampleList = [1,2,3]
PoppedValue, NewList = popElementFromList(SampleList, 20)
print(f"Popped Value:\n{PoppedValue} {type(PoppedValue)}")
print(f"New List:\n{NewList} {type(NewList)}")
Popped Value:
None <class 'NoneType'>
New List:
[1, 2, 3] <class 'list'>

使用例4

SampleList = []
PoppedValue, NewList = popElementFromList(SampleList)
print(f"Popped Value:\n{PoppedValue} {type(PoppedValue)}")
print(f"New List:\n{NewList} {type(NewList)}")
Popped Value:
None <class 'NoneType'>
New List:
[] <class 'list'>

まとめ

Pythonのリスト(配列)はPython標準で使えるデータ型であり、Pythonでプログラムする上でよく使うものとなっております。この記事では、Pythonによるリスト(配列)から要素をポップする/取り出す/抜き出す方法を紹介しました。ぜひ活用してみてください。

関連検索ワード

How to pop an element from list?

関連キーワード

python, 入門, 初心者, リスト, 配列, ポップ, 取り出し, 抜き出し, list, pop

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny