3

Let's say i have 2 following functions:

def get_items():
    items = []
    for i in xrange(2, 10):
        items.append(i)
    return items

def gen_items():
    for i in xrange(2, 10):
        yield i

I know i can use both of them in a for loop like this

for item in gen_items():
    do something

But now i need to initialize a variable as list, like this

mylist = get_items()

but with the generator function. Is there a way to do it without a for loop appending the items from generator?

4
  • 1
    mylist = list( get_items() ) Commented Oct 6, 2016 at 14:21
  • 2
    xrange is already a generator by the way Commented Oct 6, 2016 at 14:22
  • xrange returns an object which is lazy evaluated in Python 2 like the range function in Python 3. So if all your generator function is doing is iterate over the xrange object, then list(xrange(2, 10)) will work beautifully. Commented Oct 6, 2016 at 14:33
  • @Farhan.K: I know, it was just example to explain my question, i don't really have any such function on my code. Commented Oct 6, 2016 at 14:48

2 Answers 2

4

The list builtin will accept any iterator:

l = list(gen_items())
Sign up to request clarification or add additional context in comments.

Comments

3

You can just directly create it using list which will handle iterating for you

>>> list(gen_items())
[2, 3, 4, 5, 6, 7, 8, 9]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.