+ 2

Need solution in python

How the output of this code is 2? a={0:1, 1:2} _sum=0 for b in a: _sum+=b Print(_sum+b)

13th Oct 2022, 4:47 AM
Mustakim Rahman
Mustakim Rahman - avatar
2 Réponses
+ 5
When you iterate a dictionary, the loop variable will take the keys. Inside the loop you are adding all the keys to the _sum variable. That's 0+1=1. But the variable b will still hold the value of the last key. In this case, 1. Therefore the total of 2 is printed. It must be noted, that the iteration order of a dictionary, can change if you modify the dictionary (insert and remove keys), and it even depends on the python version and implementation. So it is not a good idea to rely on the last key in a serious program (in this case 'b'), at least don't take it for granted. https://stackoverflow.com/questions/2053021/is-the-order-of-a-python-dictionary-guaranteed-over-iterations Also in my opinion it is bad coding style to refer to the loop variable outside of the loop's scope, even if it is contextually available.
13th Oct 2022, 5:03 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Try to print b into for loop to understand. If you want loop dictionnary values : for b in a.values()
13th Oct 2022, 5:08 AM
Roland
Roland - avatar