-1

I've got this function that removes the second data value from a list (simplified). However when executing the function, the original list seems to get modified even though I'm only doing something to the variable inside the function.

print(data_values)

def remove_2(data):
    data.pop(2)
    return data

new_data = remove_2(data_values)
print(data_values) 

>>>['a', 'b', 'c', 'd']
>>> ['a', 'b', 'd']

I'm printing out the original data_values both times, but the second time it's the modified version even though only the variable inside the function was modified.

Zciurus
  • 1
  • 1
  • 4
    It sounds like you could use a [quick introduction to how variables and objects work in Python](https://nedbatchelder.com/text/names.html). – user2357112 Jul 20 '19 at 23:24
  • Possible duplicate of [Function changes list values and not variable values in Python](https://stackoverflow.com/questions/17686596/function-changes-list-values-and-not-variable-values-in-python). Look in this link for a detailed explanation about Python variables – Tomerikoo Jul 20 '19 at 23:47
  • You aren't modifying the variable, you are modifying the object – juanpa.arrivillaga Jul 21 '19 at 00:32

1 Answers1

0

The pop() function removes the element with the given index what you're doing is removing the element with index 2 from the original list and then using another list to display it

print(data_values) 
def remove_2(data): 
    data.pop(2) 
    return data
new_data=data_values[:]
new_data = remove_2(new_data)
print(data_values)
print(new_data) 

You should use another list if you don't want the default list to be changed

johnsnow06
  • 131
  • 7