[Tutor] Unpack arguments out of an Iterator
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Oct 8 05:32:55 EDT 2020
On 08/10/2020 02:04, Manprit Singh wrote:
> num_list = [2, 5, 8, 7, 4, 3, 1]
> odd_nums = (num for num in num_list if num % 2 != 0)
> print(*odd_nums)
> Actually I have been experimenting with iterators for long and find it very
> convenient to work, so I have developed a habit to use iterators a lot.
I think you might be meaning generators not iterators?
The above code uses a generator expression inside
parentheses to create a tuple.
In the print statement you unpack the tuple (which could
be created in any way you like)
> this example you can see that odd_nums is an iterator consisting of all odd
> numbers from the list num_list, and for printing those odd numbers, I have
> used unpacking of the iterator using (*) inside print( ) function.
All the basic Python collection types are iterators or
can be used as such. You can also unpack lists.
But not all iterators can be unpacked.
> 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.
Its correct and works and is appropriate. But that's more
to do with using a tuple data type than using iterators.
I'm not sure what other kind of feedback you are looking for.
The more normal use for iterators is in calling next() etc.
--
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