0

This seems incredibly basic, but this for some reason my list is being modified when calling a function, even though I never change the value of it.

I want to create a new list with values that are doubled, while the original list stays the same. (I need to do it with this method as opposed to something like list comprehensions, since later I want to do different things than double each term).

def DoubleList(listToDouble):
    tempList = listToDouble

    for i in range(4):
        tempList[i] *= 2

    return tempList

mainList = [100, 100, 32, 32]
print('List =', mainList) # Should print [100, 100, 32, 32]

doubledList = DoubleList(mainList)
print('Doubled list =', doubledList) # Should print [200, 200, 64, 64]

print('Final List =', mainList) # mainList was never changed, so should print [100, 100, 32, 32]?

Currently it prints:

List = [100, 100, 32, 32]
Doubled list = [200, 200, 64, 64]
Final List = [200, 200, 64, 64]  

I would have thought that doubledList would be doubled (which is working fine), but mainList would stay the same (currently it also doubles).

Is this doing exactly what it's supposed to and I'm just missing it? Thanks to any that can help! :)

Resistnz
  • 74
  • 5
  • `tempList` points to `listToDouble` - this is why the changes you do to `tempList` impact `listToDouble` – balderman Aug 31 '21 at 12:08
  • 1
    As pointed by @balderman, both variable names reference the same object. If you want to copy the list, either use `copy`, or list slicing (as `tempList = listToDouble[:]`) or even `tempList = list(listToDouble)` – MatBBastos Aug 31 '21 at 12:11
  • Why is this then affecting `mainList`? Does modifying a parameter in a function modify the variable that was passed in? – Resistnz Aug 31 '21 at 12:11
  • 1
    Please, refer to [this question](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – MatBBastos Aug 31 '21 at 12:13

1 Answers1

0

In python you cannot pass the value, you are passing a reference that means that the reference is the same list.

If you copy the list then you get the expected behaviour:

tempList = listToDouble[:]
azl
  • 109
  • 1
  • 8
  • Does this happen for all datatypes or just lists? – Resistnz Aug 31 '21 at 12:15
  • If you are asking about how Python _works_, please search for that answer and, if not found, ask a new question. [This basic article](https://realpython.com/python-variables/) on Variables in Python might aid. – MatBBastos Aug 31 '21 at 12:19
  • This applies only for lists, different datatypes have different ways to clone/copy – azl Sep 09 '21 at 10:13