3) g. Iterators and Iterables Examples




Dang Spadert has been really happy with his list that contains all of the characters of his name. He now wants to write some code in Python that looks up in his list and prints all the characters in a sequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
Output:
name = "Dang Spadert"
name_list = list(name)

char_iter = iter(name_list)

# Find out the total number of characters/elements
size_of_name = len(name_list)
print("size_of_name = ", size_of_name)

# Run a loop based on the size
for i in range(size_of_name):
  print(next(char_iter))




Dang thinks that he can perform the same iteration in Python without using the list; just his name string is enough. Is it correct? Can he use a string as iterable? Try it out!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Output:
size_of_name =  12
D
a
n
g
 
S
p
a
d
e
r
t




Dang met Domenico at a business conference, which introduced him to Python dictionaries. Dang liked this structure a lot and wants to try it out in a loop. Can Dang use a dictionary as an iterable? What would the iterator then give?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output:
item# 1 = crowd
item# 2 = bells
item# 3 = operation
item# 4 = line
item# 5 = clock
item# 6 = stamp



item# 1 = crowd
item# 2 = bells
item# 3 = operation
item# 4 = line
item# 5 = clock
item# 6 = stamp




Write again a Python iterator where this time the iterable is a tuple. Will this work? If yes, then let Enrico and Erica know that they use tuples too 😉

1
2
3
4
5
6
Output:
number_of_colors =  4
red
maroon
wine
crimson




Lang wants to kill two birds with one stone. He wants to use Enrico’s tuples and Erica’s sets in a single loop, iterate and print a pair of numbers: one that is the i-th element of the tuple and one that is the i-th element of the set. Can you do that for him? (Hint: use two different iterators and assume that both iterables have the same number of elements).

1
2
3
4
5
6
Output:
number_of_colors =  4
erica's color =  red enrico color =  red
erica'
s color =  maroon enrico color =  crimson
erica's color =  wine enrico color =  orange
erica'
s color =  crimson enrico color =  black