Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Say I have a function that creates a list of objects. If I want to return an iterator, I'll have to return iter(a_list). Should I do this, or just return the list as it is? My motivation for returning an iterator is that this would keep the interface smaller -- what kind of container I create to collect the objects is essentially an implementation detail

On the other hand, it would be wasteful if the user of my function may have to recreate the same container from the iterator which would be bad for performance.

share|improve this question
add comment

3 Answers

Return the list itself. That's quite efficient (since a copy is not made). If the caller wants an iterator, it can always call iter().

The fact that your interface returns a particular type of object isn't really a big deal in Python; duck typing often makes the exact types of objects unimportant.

share|improve this answer
1  
In this case I'd call the return value "iterable" in the documentation. Many standard library interfaces do. –  Jan Hudec May 28 '12 at 9:39
1  
I thought of this, but thought that a lot of programmers will ignore what the documentation says and assume the returned object is a will always be what it happens to be. –  Erik May 28 '12 at 15:27
    
True, but I personally don't think that forcing callers not to do the wrong thing is worth the overhead of copying the items in callers who want to iterate over the returned items more than once. –  James Youngman May 28 '12 at 19:30
add comment

Unless you have the need to traverse the list multiple times, I'd most likely you a generator. As a personal preference, I tend to favor generators to lists as the entire list is not maintained in memory. Of course, if you're not dealing with a large volume of data, it wouldn't really matter which way you go.

share|improve this answer
add comment

It seems like returning an iterator only makes sense if the underlying collection should not be modified or queried any other way, and you don't want the underlying collection to be iterated over multiple times with out the caller getting a new iterator. I might be missing some finer points of Python, though, as I am thinking about this in terms of Java's iterators.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.