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?

More than 1 year has passed since last update.

言語:python のリストについて

Last updated at Posted at 2024-02-08

※このQiitaで記事を書くのも初めてですので、誤字・脱字や読みづらい部分もあるかと思いますが、ご理解ください。

閲覧いただき、ありがとうございます!
私は、現在医療業界で働く医療従事者になります。
とある経緯からpythonを勉強中です。
ここでは自分が勉強した事を復習したり、忘れないようにするため記載いたしますので、もしもっとこうした方が良いよ、とかこれはちょっと。。。というものがあれば教えていただけますと幸いです。
※記事内容は随時更新します

①長さを取得する

記述
fruits = ["apple", "orange", "banana"]
count = len(fruits)
print(count)
出力結果
3

②リストに要素を追加(末尾に追加)

記述
fruits = ["apple", "orange", "banana"]
fruits.append("grape")
print(fruits)
出力結果
['apple', 'orange', 'banana', 'grape']

※複数追加したい場合は「リスト名.extend(追加したい複数の値)」を利用する。

③リストの末尾を削除(と取得)

記述
fruits = ["apple", "orange", "banana", "muscat"]
acquisition_fruit = fruits.pop()
print(acquisition_fruit)
出力結果
muscat

④リスト内の要素を指定して削除する

変数.remove(消したい要素)

記述
fruits = ["apple", "orange", "banana", "grape"]
fruits.remove("banana")
print(fruits)
出力結果
['apple', 'orange', 'grape']

⑤インデックス番号を指定して削除する

del 変数[削除したいindex番号]

記述
fruits = ["apple", "orange", "banana", "grape"]
del fruits[1]
print(fruits)
出力結果
['apple', 'banana', 'grape']

範囲で複数消したいときは?

記述
fruits = ["apple", "banana", "orange", "grape"]
del fruits[1:3]
print(fruits)
出力結果
['apple', 'grape']

del 変数[ 開始index : 終了index ]
上記の例として書いたコードだと
範囲はindex1〜2に格納されている値をを削除することになります。

⑥リストの要素をソートする

ソートする・・・あるルールにしたがって並べること
破壊的にソートする:sortメソッド
非破壊的にソートする:sortedメソッド
「破壊的」にというのは、元々あるリストを並べ替えて書き換えてしまうことです。
非破壊的でしたら、元々のリストは保持したまま置いておくことができます。

記述
#ここはsortメソッドの記述
fruits = ["apple","grape", "orange", "banana" ]
fruits.sort()
print(fruits)

#ここはsortedメソッドの記述
fruits2 = ["apple","grape", "orange", "banana" ]
print(sorted(fruits2))
print(fruits2)


出力結果
['apple', 'banana', 'grape', 'orange']
['apple', 'banana', 'grape', 'orange']
['apple', 'grape', 'orange', 'banana']
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?