In many case, people all ways say “use the yield to lazily create element.”
but I think everything have cost, include the yield and its iterator.
In effective nord eyes, I think it’s nice question.
so,for example, when I get an function.
def list_gen(n):
if n > MAGIC_NUM:
return xrange(n)
else:
return range(n)
How much dose the MAGIC_NUM is?
UPDATE sorry for this mistake, I’m origin meaning is compare the iterator’s cost and list cost.
UPDATE AGAIN Please imaging an case. Whether have an condition, that the memory so limit that it’s can’t create an iterator.
ha, this question is more funny now.
UPDATE AGAIN Why does create an iterator and save the yield context are less then create a list? or How much does iterator cost ?(sorry for my insult) How many bytes?
You’re mixing several things up.
This function is a generator. Calling it returns a generator object, which is an iterator.
An iterator is a thing that has
next(), i.e. it can be traversed over once. An iterator is created over something usingiterwhenever you do afor i in something.These functions are regular functions. One returns a
listand the other returns anxrangeobject. Both lists and xranges are iterable, i.e. multiple independent iterators can be created for them.So back to your question: You’re asking whether to return a
listor anxrangeobject.That depends, obviously! It depends on what you want to do with the result.
If you want to mutate it somehow, then you need a real list. Use
rangedirectly.If you only want to iterate over it, then it doesn’t make a difference semantically: both an
xrangeobject and alistreturned byrangewill produce an iterator which iterates over the same sequence.However, if you use
xrange, you’ll never create the whole list in memory. Why create a full-fledgedlistobject in memory if all you want to do is a simple iteration? You don’t need to allocate a temporary large memory buffer whenever you want aforloop, right?Hence: It’s safe to stick with
xrange, since the caller can always make alistout of it.Let’s confirm that with a benchmark. We want to know if it’s faster to iterate over xranges than over lists constructed by
range(including the cost ofrangecall, of course).Code:
Result: