Omer Khalid wrote:
Hi,

I am having a very strange problem with modifying a variable in a list in my
program. Here is the code:

# a list that contains dictionary objects
jobs = []

index=5
for each in range(index):
         jobs.append({'v':0})

some_function(index):
       if jobs[index]['v'] == 0:
                   # set it to 1
                   jobs[index]['v'] = 1
                   print "Set to 1"
      else:
                   print "Already set to 1"

loop():
        index=0
        for each in range(len(jobs)):
                 some_function(index)
                 index +=1


Apparently, the jobs[index]['v'] never get updated in the some_function but
the print statement afterwards get printed...

What's really surprising is that there are no errors or exceptions and my my
program runs in a single thread...so i have been unable to explain this
behavior.

Any insight would be much appreciated!

Cheers
Omer

There are four things to fix before the program does anything much at all. Two places you're missing the def, indentation is inconsistent, and you never actually call either of the functions. The first three are syntax errors, so presumably your cut/paste in your computer is broken.

Once I make those four corrections, I get the following output:

Set to 1
Set to 1
Set to 1
Set to 1
Set to 1

But you never said what you got, nor what you expected. That's certainly what I'd expect. And if you make a second call to loop() in your outer code, you get five copies of "Already set to 1"

BTW, there are a number of things that could be done better. The main one I'll point out is that you shouldn't re-use a global variable 'index' as a local with different meaning. As someone else pointed out, since the global is a constant, making it all uppercase is the convention.

DaveA

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to