0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python 3 エンジニア認定基礎試験 合格に向けて part6 (Python List メソッド一覧と使い方)

0
Posted at

Python List メソッド一覧と使い方

Python の list には便利なメソッドが多数あります。ここでは主要なものをまとめ、簡単な使い方例を示します。


1. append()

説明: リストの末尾に要素を追加する。

fruits = ['apple', 'banana']
fruits.append('orange')
print(fruits)  # ['apple', 'banana', 'orange']

2. extend()

説明: リストに他のリストやイテラブルを追加する。

fruits = ['apple']
fruits.extend(['banana', 'orange'])
print(fruits)  # ['apple', 'banana', 'orange']

3. insert()

説明: 指定した位置に要素を挿入する。

fruits = ['apple', 'orange']
fruits.insert(1, 'banana')
print(fruits)  # ['apple', 'banana', 'orange']

4. remove()

説明: 指定した値を削除する(最初に出てきた要素のみ)。

fruits = ['apple', 'banana', 'orange']
fruits.remove('banana')
print(fruits)  # ['apple', 'orange']

5. pop()

説明: 指定した位置の要素を削除して返す。位置未指定なら末尾。

fruits = ['apple', 'banana', 'orange']
last = fruits.pop()
print(last)    # 'orange'
print(fruits)  # ['apple', 'banana']

6. clear()

説明: リストの全要素を削除する。

fruits = ['apple', 'banana']
fruits.clear()
print(fruits)  # []

7. index()

説明: 指定した値の最初のインデックスを返す。

fruits = ['apple', 'banana', 'orange']
print(fruits.index('banana'))  # 1

8. count()

説明: 指定した値がリストに何個あるか数える。

numbers = [1,2,2,3]
print(numbers.count(2))  # 2

9. sort()

説明: リストを昇順に並べ替える。逆順は reverse=True

numbers = [3,1,2]
numbers.sort()
print(numbers)  # [1,2,3]
numbers.sort(reverse=True)
print(numbers)  # [3,2,1]

10. reverse()

説明: リストを逆順にする。

fruits = ['apple', 'banana']
fruits.reverse()
print(fruits)  # ['banana', 'apple']

11. copy()

説明: リストの浅いコピーを作成する。

fruits = ['apple', 'banana']
fruits_copy = fruits.copy()
print(fruits_copy)  # ['apple', 'banana']

💡 ポイント

  • append() は要素1つずつ追加
  • extend() はリストをまとめて追加
  • pop() は削除と取得が同時にできる
  • sort()reverse() はリスト自体を変更する(戻り値は None)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?