Here is some test code that I wrote.
class myclass:
def __init__(self, aty):
self.number = 0;
self.anitype = aty;
l = [];
l.append(myclass("tiger"))
l.append(myclass("lion"))
l.append(myclass("puma"))
l.append(myclass("jagur"))
# Method 1 : of course this doesn't work, but I saw a case where it works
#for idx in l: l[idx].number = idx
# Method 2 : of course this works
for idx, lst in enumerate(l):
l[idx].number = idx
for idx, lst in enumerate(l):
print("%d : %s" % (lst.number, lst.anitype))
The result :
0 : tiger
1 : lion
2 : puma
3 : jagur
Of course, Method 1 should not work, but today I saw some code that I received from another company and it has a line below.(only the snippets shown)
for idx in ls: ls[idx].Oi = idx
Here ls
is a list of class objects. The class has an instance member variable Oi.
Thinking this line strange, I ran the code with a debugger, and it works! The Oi values of the list member objects are being assigned 0,1,2,3,..
How does this work? By the way, this line of code is seen in a function which is not a member function of a class (it's a global function).
In Python there's a mapping type dict
. When iterating over a dictionary, you're iterating over its keys. To get the values, you still need to use the keys as indices:
d = {'a': 3, 'b': 5, 'c': 4}
for key in d:
print(key, d[key])
Output (order may vary):
a 3
b 5
c 4
It's very likely the code you see is doing this (iterating over a dict
, or another mapping object, instead of a list
). If you see something initialized like
d = {} # An empty dict
Then it's a dict
object. (Empty sets are initialized as set()
)