Files
coding-mentor-agent/kb/python-course-kb-practical-python/wiki/exercises/6-1-iteration-illustrated.md
T

1.5 KiB

id, source_exercise_id, title, section, source_path, source_repo, source_commit, student_visible_solution, has_private_solution, skip
id source_exercise_id title section source_path source_repo source_commit student_visible_solution has_private_solution skip
practical-python-6.1 6.1 Iteration Illustrated 6.1 Iteration Protocol 06_Generators/01_Iteration_protocol.md https://github.com/dabeaz-course/practical-python 93dca856b41c61a0a0f85ae334116e4c125629ea false false false

Exercise 6.1: Iteration Illustrated

Source: Practical Python Programming, 06_Generators/01_Iteration_protocol.md.

Exercise 6.1: Iteration Illustrated

Create the following list:

a = [1,9,4,25,16]

Manually iterate over this list. Call __iter__() to get an iterator and call the __next__() method to obtain successive elements.

>>> i = a.__iter__()
>>> i
<listiterator object at 0x64c10>
>>> i.__next__()
1
>>> i.__next__()
9
>>> i.__next__()
4
>>> i.__next__()
25
>>> i.__next__()
16
>>> i.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

The next() built-in function is a shortcut for calling the __next__() method of an iterator. Try using it on a file:

>>> f = open('Data/portfolio.csv')
>>> f.__iter__()    # Note: This returns the file itself
<_io.TextIOWrapper name='Data/portfolio.csv' mode='r' encoding='UTF-8'>
>>> next(f)
'name,shares,price\n'
>>> next(f)
'"AA",100,32.20\n'
>>> next(f)
'"IBM",50,91.10\n'
>>>

Keep calling next(f) until you reach the end of the file. Watch what happens.

关联来源