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

Last updated at Posted at 2025-02-23

1. 結論 - それぞれの関数の違い

違いその1 : 戻り値

  • sort() → "None"が返ってくる
  • sorted() → 並び替えられた状態の新しいListが返ってくる

違いその2 : 扱えるオブジェクトの種類

  • sort() → Listのみ
  • sorted() → Listを含むiterable*オブジェクト

スクリーンショット 2025-02-23 21.50.03.png
出典 : Pythonドキュメンテーション

補足 : iterableオブジェクトとは?

iterable

An object capable of returning its members one at a time.
Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an __iter__() method or with a __getitem__() method that implements sequence semantics.

スクリーンショット 2025-02-23 21.58.28.png
出典 : Pythonドキュメンテーション

自分なりに日本語訳してみた。

iterable

要素を1つずつ取り出し、呼び出し元に渡すことができるオブジェクトのこと。例としては、要素の並び順を管理するList、str、tupleをはじめ、要素の並び順を管理しないdict、file objects、_ iter ()、または getitem _()によって順序管理を実装されたクラスのことが挙げられます。

2. 検証

スクリーンショット 2025-02-23 22.00.48.png
*Paizaで提供されているWeb上の開発環境で検証を実施しました。

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?