8
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?

joinの書き方クイズ

Last updated at Posted at 2025-12-04

問題

次のPythonの記述はすべて同じ結果になります。
計算時間もほぼ一緒ですが、1つだけ少し時間がかかります。
その書き方はどれでしょうか?

  1. "".join(map(str, range(1_000_000)))
  2. "".join(str(i) for i in range(1_000_000))
  3. "".join([str(i) for i in range(1_000_000)])

 
 
 
 
 

解答

答えは2です。

実際に確認してみましょう。下記はPython 3.13で実行した結果です。

たしかに2番のジェネレーターだけ少し遅いです。

下記のブログによると、str.join()は、ジェネレーターを渡すとリストに変換してから計算するようです。
その変換の分だけ時間がよけいにかかると思われます。

str.join()の公式ドキュメントには、特に記述はないようです。

なお、先のブログによると、この現象はCPython特有とのことです。

まとめ

str.join()の書き方の違いによる計算時間を確認しました。
ジェネレーターとリストの内包表記が同じ結果になるとき、一般に、ジェネレーターの方が効率的です。
しかし、str.join()に限っては内包表記の方が若干効率的になります。

8
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
8
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?