LoginSignup
0
0

More than 3 years have passed since last update.

【Udemy Python3入門+応用】 17.リストの操作

Posted at

※この記事はUdemyの
現役シリコンバレーエンジニアが教えるPython3入門+応用+アメリカのシリコンバレー流コードスタイル
の講座を受講した上での、自分用の授業ノートです。
講師の酒井潤さんから許可をいただいた上で公開しています。

■リストの操作

◆リストの要素を置換する
>>> s = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> s[0] = 'A'
>>> s
['A', 'b', 'c', 'd', 'e', 'f', 'g']
>>> s[2:5] = ['C', 'D', 'E']
>>> s
['A', 'b', 'C', 'D', 'E', 'f', 'g']

リスト内のインデックスやスライスを指定して、直接文字列を代入することができる。

.append().insert()
>>> n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> n
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> n.append(100)
>>> n
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]
>>> n.insert(0, 200)
>>> n
[200, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]

.appendにより、リスト内の最後に文字列が付け加えられる。
.insertを用いると、任意のインデックスを指定し、その場所に文字列を挿入できる。

.pop()
>>> n = [200, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 300]
>>> n
[200, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 300]
>>> n.pop(0)
200
>>> n
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 300]
>>> n.pop()
300
>>> n
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

.pop()でインデックスを指定すると、その要素が抽出される。
抽出された要素はリストからなくなる。
インデックスを指定しない場合は、最後の要素が抽出される。

◆リストの要素を消去する(空のリストで置換する)
>>> s = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> s[2:5] = []
>>> s
['a', 'b', 'f', 'g']

指定した部分を空のリストに置換してやることで、要素を消去できる。

◆リストの要素を消去する(delを用いる)
>>> n = [1, 2, 3, 4, 5]
>>> n
[1, 2, 3, 4, 5]
>>> del n[0]
>>> n
[2, 3, 4, 5]
>>> del n
>>> n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

インデックスを指定したものをdelで消去できる。
うっかりインデックスを指定せずにndelをかけた場合、n自体が抹消されるため注意。

◆リストの要素を消去する(.remove()を用いる)
>>> n = [1, 2, 3, 4, 5]
>>> n
[1, 2, 3, 4, 5]
>>> n.remove(2)
>>> n
[1, 3, 4, 5]
>>> n.remove(4)
>>> n
[1, 3, 5]
>>> n.remove(6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

.remove()を用いると、要素を直接指定して消去することができる。
このときリスト内に存在しない要素を指定するとエラーとなる。

◆リストに別のリストの要素を追加する
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> x = a + b
>>> x
[1, 2, 3, 4, 5, 6]

これは前にやった通り。

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a += b
>>> a
[1, 2, 3, 4, 5, 6]

+=により、bのリスト内の要素がaのリストに付け加えられる。

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6]

.extend()というメソッドを使う方法もある。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0