[Tutor] Unpack arguments out of an Iterator
Manprit Singh
manpritsinghece at gmail.com
Thu Oct 8 10:00:56 EDT 2020
Dear sir ,
This time, i am raising a question based on your reply .
As far as i know a generator expression returns an iterator . Is my
knowledge incorrect ?
The generator expression is assigned to the variable odd_nums, and hence i
am saying that odd_nums is an iterator.
Kindly comment
Regards
Manprit Singh
On Thu, Oct 8, 2020 at 3:03 PM Alan Gauld via Tutor <tutor at python.org>
wrote:
> 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
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list