[Tutor] Unpack arguments out of an Iterator

Alan Gauld alan.gauld at yahoo.co.uk
Thu Oct 8 19:43:48 EDT 2020


On 08/10/2020 15:00, Manprit Singh wrote:

> This time, i am raising a question based on your reply .
> 
> As far as i know a generator expression returns an iterator

No you are correct, but that is like saying you like arithmetic
operators because they return numbers. Numbers are useful in
all sorts of other contexts. Likewise iterators are a far
more general concept than those returned by generator
expressions.

And the iterator aspect of the collections returned by generator
expressions has nothing much to do with your ability to unpack
them using *. That has always been a feature of python tuples and
lists. Even before iterators were introduced to the language.

These are two separate features and it wasn't clear in your first
post whether you were interested in the iterable nature of
collections or the ability to unpack from them.

> The generator expression is assigned to the variable odd_nums, and hence i
> am saying that odd_nums is an iterator.

That's correct but entirely orthogonal to your ability to unpack its
values. Python collections can be unpacked with *, they always have
been. And Python collections are iterable. But the two are not directly
connected(except perhaps at the implementation level). You can deine
your own iterables that can also be unpacked:

>>> def f(a,b,c): print(a,b,c)

>>> class three_ones:
	def __init__(self): self.count = 0
	def __iter__(self): return self   # part of iterator protocol
	def __next__(self):               # ditto
		if self.count < 3:
			self.count+= 1
			return 1
		else: raise StopIteration

		
>>> to = three_ones()
>>> f(*to)
1 1 1
>>>

So when you said:

"""I have developed a habit to use iterators a lot"""
and
"""Need your comments on the way i have used the iterator in
the above program and the way i have unpacked the values
from the iterator using (*) inside print."""

It's not clear whether you are using unpacking from collections
(aka iterators) a lot or whether you use generator expressions
a lot.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list