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の sorted() と list.sort() の違い

Posted at

sorted()関数

特徴

  • 新しいリストを返す:
    sorted()関数は、ソートされた新しいリストを返します。元のリストは変更されません。

  • イテラブル全般に対応:
    リストだけでなく、タプルや文字列など、イテラブルなオブジェクトをソートできます。

使用例

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
print(numbers)  # [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

引数

  • iterable: ソートする対象のイテラブルなオブジェクト。
  • key: ソートの基準とする関数。デフォルトはNone
  • reverse: Trueにすると降順にソートされる。デフォルトはFalse

カスタムソートの例

words = ["banana", "apple", "cherry"]
sorted_by_length = sorted(words, key=len)
print(sorted_by_length)  # ['apple', 'banana', 'cherry']

list.sort()メソッド

特徴

  • インプレースでソート:
    list.sort()メソッドは、リスト自体をソートします。元のリストが変更され、新しいリストは生成されません。

  • リスト専用:
    このメソッドはリストオブジェクト専用です。他のイテラブルには使用できません。

使用例

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

引数

  • key: ソートの基準とする関数。デフォルトはNone
  • reverse: Trueにすると降順にソートされる。デフォルトはFalse

カスタムソートの例

words = ["banana", "apple", "cherry"]
words.sort(key=len)
print(words)  # ['apple', 'banana', 'cherry']

sorted()list.sort()の違い

1. リストの変更

  • sorted():
    • 新しいリストを返す。
    • 元のリストは変更されない。
  • list.sort():
    • リスト自体をインプレースでソートする。
    • 元のリストが変更される。

2. 対応するイテラブルの種類

  • sorted():
    • リスト、タプル、文字列など、イテラブル全般に使用できる。
  • list.sort():
    • リストオブジェクト専用。

3. 戻り値

  • sorted():
    • 新しいソートされたリストを返す。
  • list.sort():
    • Noneを返す(リスト自体がソートされる)。

まとめ

  • 新しいリストが必要な場合元のリストを変更したくない場合sorted()を使う。
  • リスト自体をソートしても問題ない場合メモリ効率を考慮する場合list.sort()を使う。
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?