Karrar Ali
Karrar Ali

Reputation: 69

link lists inside function in python

I am trying to to connect the element of my lists in the function in way if I do any change on any element of

def itinerant(S1,S2,S3,S4,S5,S6,S7,S8):
    old_list=[S1,S2,S3,S4,S5,S6,S7,S8]
    outer=[S5,S6,S7,S8]
    outer_cube=[[S2,S3,S4],[S1,S3,S4],[S1,S2,S4],[S1,S2,S3]]

so for example if I make change on any of S3s on outer_cube in the 'outer_cube' list this change goes to the rest of S3s in this list and S3 'old_list' as well my function returns new_list=[S1,S2,S3,S4,S5,S6,S7,S8] with the updated elements.any suggestions would be appreciated.

Upvotes: 1

Views: 98

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

You only have one instance of the s3 variable that is being passed in as a parameter. You assign it to a bunch of lists, but they all refer to the same s3. What is an s3? If it's a python object, you'll need to deep clone it.

import copy
news3= copy.deepcopy(s3) # deep (recursive) copy    

If it's something like a dictionary, then you you can construct a copy like so dict(s3).

This means that in your code you'll need to make copies of all the the entities you want to manipulate in isolation. The second line of your code becomes:

outer=[copy.deepcopy(S5),copy.deepcopy(S6),copy.deepcopy(S7),copy.deepcopy(S8)]

Same goes with your last line.

Upvotes: 1

Related Questions