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.
#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)
Comments
Leave a comment