What will be the output of the following program ?tuple = {} tuple[(1,2,4)] = 8 tuple[(4,2,1)] = 10 tuple[(1,2)] = 12 _sum = 0 for k in tuple: _sum += tuple[k] print(len(tuple) + _sum)
Question
What will be the output of the following program ?tuple = {} tuple[(1,2,4)] = 8 tuple[(4,2,1)] = 10 tuple[(1,2)] = 12 _sum = 0 for k in tuple: _sum += tuple[k] print(len(tuple) + _sum)
Solution
The output of the program will be 33. Here's how:
-
A dictionary named
tupleis created. Despite the name, it's not a tuple but a dictionary. -
Three key-value pairs are added to the dictionary. The keys are tuples and the values are integers.
-
A variable
_sumis initialized to 0. -
A for loop iterates over the keys in the dictionary. For each key, the corresponding value is added to
_sum. -
After the loop,
_sumis 30 (8 + 10 + 12). -
The length of the dictionary is 3, because there are three key-value pairs.
-
The final line of the program prints the sum of the length of the dictionary and
_sum, which is 3 + 30 = 33.
Similar Questions
What will be the output of the following program ?tuple = (1, 2, 3, 4) tuple.append( (5, 6, 7) ) print(len(my_tuple))
Which of the following creates a tuple?tuple1=("a","b")tuple1[2]=("a","b")tuple1=(5)*2None of the above
What will be the output of the following program:dictionary = {}dictionary[1] = 1dictionary['1'] = 2dictionary[1] += 1 sum = 0for k in dictionary: sum += dictionary[k] print (sum)
What will be the output of the following Python code?l=[[1, 2, 3], [4, 5, 6]]for i in range(len(l)): for j in range(len(l[i])): l[i][j]+=10print(l)
What will be the output of the following Python code?u=[5,6,7,8]v=[sum(u[0:x+1]) for x in range(0,len(u))]print(v)
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.