0
1

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のリストの特徴

1. 順序付きコレクション

• リスト内の要素は順番が保持されます。インデックスを使って特定の要素にアクセス可能。
• インデックスは 0始まり(最初の要素が 0 番目)。

2. ミュータブル(変更可能)

• リストは作成後でも要素の追加、削除、変更が自由にできる。

3. 多様なデータ型が混在可能

• リスト内には、異なる型(文字列、数値、ブール値、リストなど)を混在させることができる。


リストの基本構文

リストは、角括弧 [] を使って作成し、リストの要素は、カンマ , で区切る。

python
fruits = ["りんご", "バナナ", "みかん"]
numbers = [1, 2, 3, 4, 5]
mixed = ["文字列", 123, True, 4.56]  # 異なるデータ型を含むことも可能

リストの基本操作

1. 要素のアクセス

リストの要素には、インデックス(位置番号)を使ってアクセスします。インデックスは0から始まる。

python
fruits = ["りんご", "バナナ", "みかん"]
print(fruits[0])  # りんご
print(fruits[1])  # バナナ
print(fruits[-1]) # みかん(負のインデックスは末尾からアクセス)

2. 要素の変更

特定のインデックスの値を変更できる。

python
fruits[1] = "オレンジ"  # "バナナ"を"オレンジ"に変更
print(fruits)  # ['りんご', 'オレンジ', 'みかん']

3. 要素の追加

• append(): リストの末尾に要素を追加。
• insert(): 指定した位置に要素を挿入。

python
fruits.append("ぶどう")  # 末尾に追加
print(fruits)  # ['りんご', 'バナナ', 'みかん', 'ぶどう']

fruits.insert(1, "いちご")  # インデックス1に挿入
print(fruits)  # ['りんご', 'いちご', 'バナナ', 'みかん', 'ぶどう']

4. 要素の削除

• remove(): 指定した値を削除。
• pop(): 指定した位置(または末尾)の値を削除して返す。
• del: 指定した位置の値を削除。
• clear(): リストの全要素を削除。

python
fruits.remove("バナナ")  # "バナナ"を削除
print(fruits)

fruits.pop()  # 最後の要素を削除して返す
print(fruits)

del fruits[0]  # インデックス0の要素を削除
print(fruits)

fruits.clear()  # リストを空にする
print(fruits)  # []

リストの便利な機能

1. リストの長さ

python
fruits = ["りんご", "バナナ", "みかん"]
print(len(fruits))  # 3

2. リストの結合

python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined)  # [1, 2, 3, 4, 5, 6]

3. スライス(部分リストの取得)

python
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])  # [2, 3, 4] (インデックス1から3まで)
print(numbers[:3])   # [1, 2, 3] (最初からインデックス2まで)
print(numbers[2:])   # [3, 4, 5] (インデックス2から最後まで)

4. リストの繰り返し処理

python
for fruit in fruits:
    print(fruit)  # リスト内の要素を順に出力

5. リスト内包表記(リスト生成の簡略化)

python
# 1から10までの2乗をリストに格納
squares = [x**2 for x in range(1, 11)]
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

まとめ

• Pythonのリストは、柔軟性が高く、使いやすいデータ構造。
• 追加、削除、変更、検索、並び替えなどの操作が簡単に行える。
• 内包表記を使うことで、効率的なリスト生成が可能。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?