Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unpack iterator

I know *operator in Python is used to unpack iterable, such as unpack a list.

However, in practice, we also use * operator to unpack iterator, but I haven't found a document explaining it.

See example:

>>> a = [1,2,3]
>>> print(a)
[1, 2, 3]

unpack iterable

>>> print(*a)
1,2,3

unpack iterator

>>> it = iter(a)
>>> print(*it)
1,2,3
like image 203
Zhenyi Lin Avatar asked May 29 '26 02:05

Zhenyi Lin


1 Answers

asterisk * is iterable unpacking operator

Iterable is an object, which one can iterate over. It generates an Iterator when passed to iter() method. Iterator is an object, which is used to iterate over an iterable object using next() method. Iterators have next() method, which returns the next item of the object.

Note that every iterator is also an iterable, but not every iterable is an iterator.

(from geeksforgeeks)

in your example your iterator is an iterable so you can apply * the iterable unpacking operator

you can have a look over PEP 448

like image 60
kederrac Avatar answered May 30 '26 16:05

kederrac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!