I know that it's possible to convert generators into lists at a "low-level" (eg. list(i for i in xrange(10))
), but is it possible to do the reverse without iterating through the list first (eg. (i for i in range(10))
)?
Edit: removed the word cast
for clarity in what I'm trying to achieve.
Edit 2: Actually, I think I may have misunderstood generators at a fundamental level. That'll teach me to not post SO questions before my morning coffee!
A generator is a special kind of iterator—the elegant kind. A generator allows you to write iterators much like the Fibonacci sequence iterator example above, but in an elegant succinct syntax that avoids writing classes with __iter__() and __next__() methods.
Yes, We can create a generator by using iterators in python Creating iterators is easy, we can create a generator by using the keyword yield statement. Python generators are an easy and simple way of creating iterators. and is mainly used to declare a function that behaves like an iterator.
Use the __iter__() and __next__() Method to Convert Object to Iterator in Python. As the name suggests, an iterator returns the data values one by one. The iterator object does this with the help of the __iter__() and the __next__() method. The __iter__() and __next__() method together form the iterator protocol.
Try this: an_iterator = iter(a_list)
... docs here. Is that what you want?
You can take a list out of an iterator by using the built-in function list(...)
and an iterator out of a list by using iter(...)
:
mylist = list(myiterator) myiterator = iter(mylist)
Indeed, your syntax is an iterator:
iter_10 = (i for i in range(10))
instead of using [...]
which gives a list.
Have a look at this answer Hidden features of Python
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With