CSE 1010 Lecture Notes - Lecture 27: Iterator, Iter, Init
CSE 1010 verified notes
27/29View all
Document Summary
Cse 1010 - introduction to computing for engineers. Consider how a for loop works for var in collection : body of loop. For every element in collection (one at a time), put that element in var and. The collection can be a list, string, dictionary, or anything that can be iterated execute body of loop one time over. Example using a for loop: lst = [10, 20, 30] for x in lst: print(x) Example of the above for loop but using a while loop: lst = [10, 20, 30] i = iter(lst) try: while true: x = next(i) print(x) Given an iterator, the next function either: Extracts the next value from the iterator, or: Raises an exception if there are no values. You can create your own iterator so that an instance of your class can be used in a for. An instance of your class can either (you class is iterable): loop.