Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify values of a list while iterating over it in Python? [duplicate]

Tags:

python

For example:

def update_condition(self, type, params):
    for condition in self.conditions:
        condition_loaded = json.loads(condition)
        if condition_loaded['type'] == type:
            condition_loaded['params'] = params
            condition = json.dumps(condition_loaded)

The above code does nothing because condition isn't by reference. What's the proper way to do this?

like image 619
Joren Avatar asked Jan 18 '13 19:01

Joren


1 Answers

You could use enumerate:

def update_condition(self, type, params):
    for i,condition in enumerate(self.conditions):
        condition_loaded = json.loads(condition)
        if condition_loaded['type'] == type:
            condition_loaded['params'] = params
            self.conditions[i] = json.dumps(condition_loaded)

But, in general, these things are a little cleaner with helper functions and list comprehensions:

def helper(condition,type,params)
    loaded = json.loads(condition)
    if loaded['type'] == type:
       loaded['params'] = params
       return json.dumps(loaded)
    return condition

...

def update_condition(self, type, params):
    self.conditions = [helper(c,type,params) for c in self.conditions]

It should be noted that this second solution doesn't update the list in place -- In other words, if you have other references to this list, they won't be influenced. If you want, you can make the substitution in place pretty easily using slice assignment:

def update_condition(self, type, params):
    self.conditions[:] = [helper(c,type,params) for c in self.conditions]
like image 130
mgilson Avatar answered Sep 20 '22 01:09

mgilson