Reputation: 89
Basically I want this code to yield the element 0 of the list and update the list so next time it will yield the next element. Instead I get this error:
"TypeError: 'NoneType' object has no attribute '__getitem__' "
import random
def deterministicNumber():
return next(gener())
def gener():
listy = [10,12,14,16,18,20]
while True:
listy = listy[1:].append(listy[0])
print listy
yield listy[0]
return
Upvotes: 0
Views: 263
Reputation: 5864
It sounds like you want to return the numbers forever.
def listy(array):
i = 0
while 1:
yield array[i % len(array)]
i += 1
for l in listy(['a', 'b', 'c']):
print l
if you only wanted to do this one loop:
def listy(array):
i = 0
while i < len(array):
yield array[i]
i += 1
for l in listy(['d', 'e', 'f']):
print l
Upvotes: 0
Reputation: 16403
Looks like you want an iterator that cycles repeatedly through your list.
You better use the function cycle from the itertools module for this task:
>>> import itertools
>>> gener = itertools.cycle([10,12,14,16,18,20])
>>> def deterministicNumber(it):
return next(it)
>>> for _ in range(10):
print(deterministicNumber(gener))
10
12
14
16
18
20
10
12
14
16
Upvotes: 2
Reputation: 362944
listy = listy[1:].append(listy[0])
This line assigns listy = None
, because list.append
method operates in place and returns None
. Then in the next iteration of the loop, your TypeError
is caused by accessing None[1:].append(None[0])
For a one-shot iterator on the list, you can simply use instead:
gener = iter([10,12,14,16,18,20])
Upvotes: 3
Reputation: 15433
No need to update the list.
def gener():
listy = [10,12,14,16,18,20]
for item in listy:
yield item
Upvotes: 0