> Of the top of my head, I can’t think of a single non-contrived example of using a bare iterator in case that is not specifically doing something “special”.
Calling iter on a container is hardly the only way to get an Iterator. You also get Iterators from open, map, filter, zip, genexprs, generator functions, most itertools functions, etc.
thanks -- I was being pretty brain dead.
But most of those are usually immediately iterated over again.So in common use, I'd say the fileobject from open() is a biggie -- that's one of the few where folks will commonly do something other than simply iterate over the whole thing at once anyway.
In fact, I think files are one of the most common ways people learn about iterators. There are certainly a lot of StackOverflow dups asking why `for line in file:` gives them no lines when just 10 lines earlier the same file had 20 lines.
EXACTLY ! here we have it -- the most common case of folks working directly with a iterator, and they are confused with "for". So first() wouldn't add any new source of confusion.
Yes, I can see that folks might do somethig like:
my_file - open(something)
the_header = first(my_file)
and then later on be surprised that another call to first() produces a different result. But I think they'd only be surprsed once :-)
and file objects are a bit special, because they have a whol other API:
my_file.readline()
in fact, In my code, and most code I've seen, that's exactly what's used:
# get the header
header = my_file.readline()
# parse the rest
for line in my_file():
do_something(line)
I could use next() instead of readline() but I never do. Probably because I learned Python long before files were an iterator. But I don't' see newbies doing it, either. (of course, I'm not teaching it that way ;-) ). But I'm not sure it's just that - I think it's because most of us are writing that kind of code to deal with any foile-like object, not any generic iterator.
As in: a file object happens to be an iterator (so I can put it in a for loop), rather than a file object is an iterator, that happens to have some other methods for working with it.
Now that I think about it, that's also the case with sequences -- we think of the fact that we are working with a list, and it also happens to be an iterable, so we can put it in a for loop. rather than thinking about writing general code for any iterator, that might be a sequence.
Which is why I'd use a_list[0], rather than next(iter(a_list)).
but I can't use dict.keys()[0], for instance.
So it would be nice to have a way to do that that was more obvious than:
next(iter(d.keys())
-CHB
--