Kos Kos - 2 months ago 8
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:

friendlies.append("something")


so that friendlies now contains:

["something"]


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

["something"]


?

Answer

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']
['something']