ovod
ovod

Reputation: 1178

iterate over a list as iterator in python

I have a function which returns a list of objects (I used the code below for example). Each object has attribute called text:

def mylist():
    mylist = []
    for i in range(5):
        elem = myobject(i)
        mylist.append(elem)
    return mylist

for obj in mylist():
    print obj.text

How can I rewrite this code so mylist() returned each iteration new value and I iterate over iterator? In other words how can I reuse here a mylist in python so use it like xrange()?

Upvotes: 0

Views: 1038

Answers (4)

user3826929
user3826929

Reputation: 449

llist = [0,4,5,6] 
ii = iter(llist) 
while (True): 
    try: 
        print(next(ii)) 
    except StopIteration: 
        print('End of iteration.') 
        break 

Upvotes: 0

georg
georg

Reputation: 214949

If I understood right, you're looking for generators:

def mylist():
    for i in range(5):
        elem = myobject(i)
        yield elem

Complete code for you to play with:

class myobject:
    def __init__(self, i):
        self.text = 'hello ' + str(i)

def mylist():
    for i in range(5):
        elem = myobject(i)
        yield elem

for obj in mylist():
    print obj.text

Upvotes: 3

Bubai
Bubai

Reputation: 280

What georg said, or you can return the iter of that list

def mylist():
    mylist = []
    for i in range(5):
        mylist.append(myobject(i))
    return iter(mylist)

probably not a good idea to use your function name as a variable name, though :)

Upvotes: 3

Exelian
Exelian

Reputation: 5888

You can also use a generator expression:

mylist = (myobject(i) for i in range(5))

This will give you an actual generator but without having to declare a function beforehand.

Please note the usage of parentheses instead of brackets to denote a generator comprehension instead of a list comprehension

Upvotes: 3

Related Questions