Some raugh notes on Python Iterable Objects [10 Sep 2009]
enumerate
Enumerate creates an <enumerate> object which is iterable thank to its 'next()' method. Enumerate output is a list composed by tuples. The tuples provide the element index and the list element.
usage:
list = ['first' , 'second' , 'third'] for i in enumerate(list): print i
output:
(0, 'first') (1, 'second') (2, 'third')
!Tips:
- As always the first element index is 0, the others follow.
map
to do.
keyword: yield[24 Oct 2011]
Description
yield is a very powerful keyword, used to build generators (iterators). In python, iterators are those objects which have a next() method, used to go through our object getting all the subobjects one-by-one.
How yield works: it must be placed into a function; when the python interpreter arrive to the yield keyword he returns the value/values it declares (actually yield is like a print command) and contextually it frozes the function session saving everything to memory. Your very next access to that function will make the python interpreter to continue after the yield instruction.
How to use it
To build your own generator you have to:
- write a function with a loop inside it
- use the keyword yield inside the loop above
- in your main program, assign the funcion to a variable myvariable
- in your main program use the myvariable.next() method to get a myvariable subitem each call
Examples
Fiboncacci sequence:
def fib():
a, b = 0, 1
while 1:
yield b
a, b = b, a+b
fibonacci = fib()
print fibonacci.next()
print fibonacci.next()
...
of course you can use a loop to manage your results:
for next_item in fibonacci:
print next_item
or
while True:
print fibonacci.next()
Get next record
def get_next_record(tab):
if select not in tab:
return False
query_all = tab.select()
for record in query_all:
yield record
records = get_next_record(MyTab)
print records.next()
print records.next()
Where, in my very case, MyTab is a sqlobject.SQLObject object (a SQL table).
