#Python's container iteration
Tuples, lists, dictionaries, and sets are all iterable objects, and their elements can be accessed one by one using a for
loop:
#Tuple
Iterating through elements in a tuple:
students:tuple[str, str, str] = ("Tom", "Jerry", "Spike")
for student in students:
print(student)
#List
Iterating through elements in a list:
students:list[str] = ["Tom", "Jerry", "Spike"]
for student in students:
print(student)
#Dictionary
Iterating through a dictionary yields keys by default:
score_list:dict[str,int] = {
'Tom': 88,
'Jerry': 99,
'Spike': 66
}
for key in score_list:
print(key, score_list[key])
#Set
Iterating through elements in a set:
fruits:set[str] = {'Apple', 'Orange', 'Strawberry', 'Banana', 'Pineapple'}
for fruit in fruits:
print(fruit)
#String
A string is also an iterable object, which yields characters one by one:
text:str = "hello world"
for word in text:
print(word)