Reputation: 22113
I created a snippet of code to test the variable declaration,
In [37]: price = {"apple": 3, "orange":1}
In [38]: for key in price:
...: fruit = key
In [39]: fruit
Out[39]: 'orange'
It works without efforts to declare variable fruit in advance,
Nonetheless,
In [44]: cars = {}
In [45]: for key in cars:
...: car = key
In [46]: car
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-46-38f6ffefbd69> in <module>
----> 1 car
NameError: name 'car' is not defined
It prompt car is not defined,
In [51]: for key in cars:
...: print(type(car), dir(car))
#it output nothing, key is None
but None
can be assigned to car
In [52]: car = None
In [53]: car
In [54]: i = car
In [55]: i
It is not report error that i is not defined
,
What's the difference of the two cases?
Upvotes: 0
Views: 79
Reputation: 26037
price = {"apple": 3, "orange":1}
for key in price:
fruit = key
print(fruit)
This one iterates through keys in dictionary. When you simply do a loop through dictionary (like for x in dictionary
), you iterate through its keys. In your loop, you are assigning key to the same variable not a list or any other data structure, so you replace everytime in the loop.
cars = {}
for key in cars:
car = key
print(car)
Here, for
loop does not iterate since dictionary is empty so Python can't identify what car
is.
Dictionary empty means there is no item inside it, not even None
:
cars = {}
print(cars)
# {}
Upvotes: 1
Reputation: 1350
Cars
does not have any keys in it (no pun intended), so the statement car = key
will never be executed.
For the case with i = car
, well i just becomes a reference to the same location that car is pointing to when you state i = car
, so its not a surprise it will return the same value as car.
Upvotes: 1
Reputation: 20224
You misunderstand how it works.
You have an empty dict, there is even no None
in it. And iterating an empty collection is just ignored. So the for
loop doesn't execute at all.
Python is a complete OO language which means every element in it is an object. So is None
. You can add None
into a collection. It will show you there is a None
. But in your case, there is just nothing.
Upvotes: 1
Reputation: 1236
The difference is variable initialization. For example...
car = None
...sets the "car" variable to None. In the first example outlined, on line 46 "car" is not defined because the loop never iterates and variable is never initialized (since "cars" is an empty dict).
Upvotes: 1