0
1

More than 3 years have passed since last update.

組み込みのデータ型を勉強する(1) リスト型

Last updated at Posted at 2020-03-13

本記事について

組み込みのデータ型のうちリスト型についてまとめる

・Python3を想定
・コードに対して説明が少なめ

リストの基本情報

定義
・Pythonでリストを定義するには, [ ]を用いる.
・[ ]の中に要素を並べ, それらを",(カンマ)"で区切る.

>>> animal = ['cow', 'horse', 'fox', 'rabbit', 'monkey']

要素の取り出し

>>> animal = ['cow', 'horse', 'fox', 'rabbit', 'monkey']
>>> animal[0]
'cow'
>>> animal[-1]
'fox'
>>> animal[1:3]
['horse', 'fox']

要素入れ替え

>>> animal[0] = 'dog'
['dog', 'horse', 'fox', 'rabbit', 'monkey']

要素の追加・削除

>>> animal = ['cow', 'horse', 'fox', 'rabbit', 'monkey']
>>> animal + ['dog', 'cat'] #要素の追加
['cow', 'horse', 'fox', 'rabbit', 'monkey', 'dog', 'cat']
>>> del animal[5] #要素の削除
>>> animal
['cow', 'horse', 'fox', 'rabbit', 'monkey', 'cat']

リストの長さ

>>> len(animal)
5

リストで使えるメソッド一覧

1) list.append(x)

>>> animal = ['cow', 'horse', 'fox', 'rabbit', 'monkey']
>>> animal.append('dog')
['cow', 'horse', 'fox', 'rabbit', 'monkey', 'dog']

2) list.count(x)

>>> animal = ['cow', 'horse', 'fox', 'rabbit', 'monkey', 'cow']
>>> animal.count('cow')
2

3) list.reverse()

>>> animal = ['cow', 'horse', 'fox', 'rabbit', 'monkey']
>>> animal.reverse()
['monkey', 'rabbit', 'fox', 'horse', 'cow']
0
1
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
1