[Tutor] Unpack arguments out of an Iterator
Manprit Singh
manpritsinghece at gmail.com
Wed Oct 7 21:04:46 EDT 2020
Dear sir ,
Consider a problem, in which I have to print all odd numbers inside a list
. I would prefer solving this problem by writing the code as given below :
num_list = [2, 5, 8, 7, 4, 3, 1]
odd_nums = (num for num in num_list if num % 2 != 0)
print(*odd_nums)
The answer is 5 7 3 1 , which is the right answer .
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. In
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.
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.
Regards
Manprit Singh
Need your comments, on this program
More information about the Tutor
mailing list