Kos Kos - 1 year ago 69
Python Question

How to update a composite list as contents of member lists are changed?

Let's say I have:

friendlies = []
enemies = []
everyone = [friendlies + enemies]

And I say:


so that friendlies now contains:


What is the pythonic way to make it so that
updates as well? So that if I update
in the way stated above,
would contain:



Answer Source

Maintain a reference to friendlies and enemies in the composite list:

everyone = [friendlies, enemies]
#                     ^

Index 0 and 1 of the compisite list will reference friendlies and enemies respectively.

friendlies + enemies creates a new list which is not what you want.

A more readable approach will be making everyone a dictionary:

everyone = {'friendlies': friendlies, 'enemies': enemies}

And can be used as:

>>> friendlies = []
>>> enemies = []
>>> everyone = {'friendlies': friendlies, 'enemies': enemies}
>>> friendlies.append("something")
>>> everyone['friendlies']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download