Lecture 13 Iterators Generators
Lecture 13 Iterators & Generators
Announcements
Announcements
0olod山sen ach of hi th notion that Ardu th bodyt Thamy Iterators ody My kArhur-Den Dent,and a an inch ofs ach!【had a weak-beant y fect of the ad From te hcn6oe装是cn4料 fthfromof me. e my pooe bean pves ot in weirnga rabht bone in h se panfolly thranbocn something tha ht check prcuadyy e'd been hopingArhar overwhdofbac d shook it owy of thing of him stood the ed Aid he had supposedy Hey nervouy Hetu beard Hepo nfachestl had the itboent Hepulledd ohedu fe playing illybo Wah e Dntsed the creure.n
Iterators
Definitions Lazy evaluation-Delays evaluation of an expression until its value is needed Iterable-An object capable of returning its members one at a time. Examples include all sequences (lists,strings,tuples)and some non-sequence types(dictionaries). Iterator-An object that provides sequential access to values,one by one. o All iterators are iterables.Not all iterables are iterators. Metaphor:Iterables are books Iterators are bookmarks
Definitions ● Lazy evaluation - Delays evaluation of an expression until its value is needed ● Iterable - An object capable of returning its members one at a time. Examples include all sequences (lists, strings, tuples) and some non-sequence types (dictionaries). ● Iterator - An object that provides sequential access to values, one by one. ○ All iterators are iterables. Not all iterables are iterators. ● Metaphor: Iterables are books & Iterators are bookmarks
two tvhveotvdiloreethree Iterators oneone one How do we create iterators? >>>s [1,2,3]the book >>one,two iter(s),iter(s) iter(iterable):Return an iterator >>next(one)#move bookmark 1 over the elements of an iterable value. 入 This method creates a bookmark from a book starting at the front. >>next(two)#move bookmark 2 1 next(iterator):Returnthenext >>next(one)#move bookmark 1 element in an iterator. 2 Returns the current page and >>next(two)#move bookmark 2 moves the bookmark to the next 2 page. >>three iter(two) The iterator remembers where you >>next(three)#move bookmark 2 3 left off.If the current page is the 3 end of the book,error. >>next(two)#Ran out of pages Stop Iteration
Iterators How do we create iterators? iter(iterable): Return an iterator over the elements of an iterable value. - This method creates a bookmark from a book starting at the front. next(iterator): Return the next element in an iterator. - Returns the current page and moves the bookmark to the next page. - The iterator remembers where you left off. If the current page is the end of the book, error. >>> s = [1, 2, 3] # the book >>> one, two = iter(s), iter(s) one two one two two + three one two + three >>> next(one) # move bookmark 1 1 >>> next(two) # move bookmark 2 1 >>> next(one) # move bookmark 1 2 >>> next(two) # move bookmark 2 2 >>> three = iter(two) >>> >>> next(three) # move bookmark 2 & 3 3 >>> next(two) # Ran out of pages Stop Iteration two