Answer to Question #171426 in Python for Paul Carpenter

Question #171426

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
Expert's answer
2021-03-13T08:15:29-0500
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)



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