What is the purpose in Python's itertools.repeat?

后端 未结 6 1872
我寻月下人不归
我寻月下人不归 2020-12-01 02:02

Every use I can think of for Python\'s itertools.repeat() class, I can think of another equally (possibly more) acceptable solution to achieve the same effect. For example:<

6条回答
  •  萌比男神i
    2020-12-01 02:08

    Your example of foo * 5 looks superficially similar to itertools.repeat(foo, 5), but it is actually quite different.

    If you write foo * 100000, the interpreter must create 100,000 copies of foo before it can give you an answer. It is thus a very expensive and memory-unfriendly operation.

    But if you write itertools.repeat(foo, 100000), the interpreter can return an iterator that serves the same function, and doesn't need to compute a result until you need it -- say, by using it in a function that wants to know each result in the sequence.

    That's the major advantage of iterators: they can defer the computation of a part (or all) of a list until you really need the answer.

提交回复
热议问题