Does readlines() return a list or an iterator in Python 3?

snakile picture snakile · Aug 22, 2010 · Viewed 34.6k times · Source

I've read in "Dive into Python 3" that:

"The readlines() method now returns an iterator, so it is just as efficient as xreadlines() was in Python 2".

See: Appendix A: Porting Code to Python 3 with 2to3: A.26 xreadlines() I/O method.

I'm not sure that's true because they don't mention it here: http://docs.python.org/release/3.0.1/whatsnew/3.0.html . How can I check that?

Answer

Scott Griffiths picture Scott Griffiths · Aug 22, 2010

The readlines method doesn't return an iterator in Python 3, it returns a list

Help on built-in function readlines:

readlines(...)
    Return a list of lines from the stream.

To check, just call it from an interactive session - it will return a list, rather than an iterator:

>>> type(f.readlines())
<class 'list'>

Dive into Python appears to be wrong in this case.


xreadlines has been deprecated since Python 2.3 when file objects became their own iterators. The way to get the same efficiency as xreadlines is instead of using

 for line in f.xreadlines():

you should use simply

 for line in f:

This gets you the iterator that you want, and helps to explain why readlines didn't need to change its behaviour in Python 3 - it can still return a full list, with the line in f idiom giving the iterative approach, and the long-deprecated xreadlines has been removed completely.