Does readlines() return a list or an iterator in Python 3?
Does readlines() return a list or an iterator in Python 3?
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Track title: CC C Schuberts Piano Sonata No 13 D
--
Chapters
00:00 Question
00:39 Accepted answer (Score 28)
00:59 Answer 2 (Score 41)
02:03 Answer 3 (Score 7)
02:34 Thank you
--
Full question
https://stackoverflow.com/questions/3541...
Question links:
[Appendix A: Porting Code to Python 3 with 2to3: A.26 xreadlines() I/O method]: https://diveintopython3.problemsolving.i...
[http://docs.python.org/release/3.0.1/wha...]: http://docs.python.org/release/3.0.1/wha...
Answer 1 links:
[deprecated since Python 2.3]: http://www.python.org/download/releases/.../
[you should use simply]: http://docs.python.org/library/2to3.html...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #iterator #python3.x #readlines
#avk47
ANSWER 1
Score 44
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():
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.
ACCEPTED ANSWER
Score 28
Like this:
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('/junk/so/foo.txt')
>>> type(f.readlines())
<class 'list'>
>>> help(f.readlines)
Help on built-in function readlines:
readlines(...)
Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
>>>
ANSWER 3
Score 7
Others have said as much already, but just to drive the point home, ordinary file objects are their own iterators. So having readlines() return an iterator would be silly, because it would just return the file you called it on. You can use a for loop to iterate over a file, like Scott said, and you can also pass them straight to itertools functions:
from itertools import islice
f = open('myfile.txt')
oddlines = islice(f, 0, None, 2)
firstfiveodd = islice(oddlines, 5)
for line in firstfiveodd:
print(line)