0

I am generating triples of numbers and trying to put them in a list which I will later process. In the code below Iā€™m adding a triple Elt to a list L with one triple. How can I keep future changes to Elt from modifying L? Should be super easy, but how?

L = [[2, 3, 4]]
Elt = [5, 6, 7]
def proc1(BigList, NewElt):
    BigList = BigList + [NewElt.copy()]
    return(BigList)

print(L)
L = proc1(L, Elt)
print(L)
Elt[1] = 70 # now L[1] is different from Elt
print(L)
print(Elt)

Output:
[[2, 3, 4]]
[[2, 3, 4], [5, 6, 7]]
[[2, 3, 4], [5, 6, 7]]
[5, 70, 7]

EDIT: In fact, I was looking for call-by-value. Now I understand. Thanks!

1 Answers1

1

You can create copy of the list and use that instead. There is couple of ways how to copy list in Python, see here.

For example:

def proc1(BigList, NewElt):
    BigList = BigList + [NewElt[:]]
    return(BigList)
Community
  • 1
  • 1
ThePavolC
  • 1,693
  • 1
  • 16
  • 26
  • In the `Elt` in the list are actually supposed to be non-modifyable, `tuple(NewElt)` might be a better way. ā€“ tobias_k Jun 20 '15 at 21:41
  • That;s true, but it's really up to author. To me it seemed like the problem in the question was caused by passing reference of the list. But if you really want a list data structure which items can't be modified, then tuple is the way to go. ā€“ ThePavolC Jun 20 '15 at 21:47