Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert a list-type into a generator without iterating through?

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!

like image 451
Phillip B Oldham Avatar asked May 09 '11 07:05

Phillip B Oldham


People also ask

Is generator an iterator or iterable?

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.

How iterator can be used to generate the generator?

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.

How do you convert a list into iterable in Python?

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.


2 Answers

Try this: an_iterator = iter(a_list) ... docs here. Is that what you want?

like image 97
John Machin Avatar answered Sep 20 '22 02:09

John Machin


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

like image 45
Don Avatar answered Sep 18 '22 02:09

Don