-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path023-next.py
More file actions
49 lines (42 loc) · 1.83 KB
/
023-next.py
File metadata and controls
49 lines (42 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
Return the next item in an iterator
-----------------------------------
Input (iterator) iter() object
(value) [optional] default return value when iter reaches its end
Return (value) next item in the iterator
default value when iter reaches its end
without default value next() raises error when iter reaches
its end
"""
# Iterator contains a list
cars = iter(["Audi", "BMW", "Chrysler", "Dodge"])
cars_list = ["Audi", "BMW", "Chrysler", "Dodge"]
print('Cars: {}'.format(cars_list))
print('Iterator: {}'.format(cars))
next_cars = next(cars)
print('\nFirst "next_cars": {}'.format(next_cars))
next_cars = next(cars)
print('\nSecond "next_cars": {}'.format(next_cars))
next_cars = next(cars)
print('\nThird "next_cars": {}'.format(next_cars))
next_cars = next(cars)
print('\nFourth "next_cars": {}'.format(next_cars))
# Fifth iteration doesn't work because of the iterator contains only 4 items
# next_cars = next(cars)
# print('\nFifth "next_cars": {}'.format(next_cars))
# Using default values prevent iteration error
cars_2 = iter(["Audi", "BMW", "Chrysler", "Dodge"])
next_cars_2 = next(cars_2, "Ford") # 1
print('\n\nFirst "next_cars_2": {}'.format(next_cars_2))
next_cars_2 = next(cars_2, "Ford") # 2
print('\nSecond "next_cars_2": {}'.format(next_cars_2))
next_cars_2 = next(cars_2, "Ford") # 3
print('\nThird "next_cars_2": {}'.format(next_cars_2))
next_cars_2 = next(cars_2, "Ford") # 4
print('\nFourth "next_cars_2": {}'.format(next_cars_2))
next_cars_2 = next(cars_2, "Ford") # 5
print('\nFifth "next_cars_2": {}'.format(next_cars_2))
next_cars_2 = next(cars_2, "Ford") # 6
print('\nSixth "next_cars_2": {}'.format(next_cars_2))
next_cars_2 = next(cars_2, True) # 7
print('\nSeventh "next_cars_2": {}'.format(next_cars_2))