Answer to Question #105518 in Python for elly

Question #105518
Describe How Tuples Can Be Useful With Loops Over Lists And Dictionaries, And Give Python Code Examples. Create Your Own
1
Expert's answer
2020-03-17T14:11:26-0400

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 returnes 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 returnes 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: #llop over the both lists together
    print(a,b)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS