Answer to Question #196152 in Python for FORTUNE AIDOO

Question #196152

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-05-20T12:10:30-0400
#a tuple can be used to iterate over several lists at once in a loop.
#for this you can use the zip function:
l1 = [1,2,3] 
l2 = [True, False, True] 
l3 = ['a', 'b', 'c']
z = list(zip(l1, l2, l3))
print('zipped = ',z)
for el, el2, el3 in z:
    print(el, el2, el3)


#also a tuple can be used with dictionaries in a loop like this:
#apply the items() method to a dictionary that returns a set of tuples (key, value)


D = {'first': 1, 'second': 2, 'third': 3}
lst = list(D.items())
print('D.items() = ',lst)
for x, y in lst: 
    print('key: ', x, '; value: ',y)


#enumerate function creates a sequence of tuples, where the first element in the tuple is the index of the element
#(starting at zero by default) and the second element of the tuple is the element from the list


lst = ['zero', 'one', 'two', 'three']
for i, item in enumerate(lst): 
    print(i, item) 

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