Describe how tuples can be useful with loops over lists and dictionaries, and give Python code examples. Create your own code examples.
dic = {'model':'BMW','color':'black','produced country':'Germany'} #example of dictinary
l = list(dic.items()) #list of key,value pairs, which are tuples
print('dic.items() = ',l) #returns collection of tuples(useful)
print('Type of dic.items() is',type(l))
for k,v in dic.items(): #loop over the dictionary using key,value tuples
print('The car', k, 'is',v)
#Tuples are useful loops with zip() function
l1 = [1,2,3]
l2 = [4,5,6]
zip_ = list(zip(l1, l2)) #list of tuples with the A and B lists elements
print('Type of zipped elements is ',type(zip_))
for a,b in zip_:
print(a,b)
Comments
Leave a comment