Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code examples. Do not copy them from the textbook or any other source.
Your descriptions and examples should include the following: the zip function, the enumerate function, and the items method.
1. Tuples can be useful with loops over dictionaries in the following way. To iterate over all dictionary elements one can use method d.items() which returns the collection of tuples with following content: (key, value) of original dictionary. See example below:
d={'Name':'Isaac','Surname':'Newton','Town':'Woolsthorpe'} #example of dictinary
L = list(d.items()) #list of key,value pairs, which are tuples
print('d.items() = ',L)
print('Type of d.items() elements is ',type(L[1]))
for k,v in d.items(): #loop over the dictionary using key,value tuples
print('The key is ', k, ', the value is ',v)
2. Tuples can be useful with loops over lists in the following way. To iterate two lists together in one loop one can use function zip() that returns the collection of tuples (a,b) where a is i-t element of the first list, b is a i-th element of the second list. See example below:
A = [1,2,3] #first list
B = [4,5,6] #second list
zipped = list(zip(A, B)) #list of tuples with the A and B lists elements
print('zipped = ',zipped)
print('Type of zipped elements is ',type(zipped[1]))
for a,b in zipped: #loop over the both lists together
print(a,b)
Comments
Leave a comment