-3

We recently encountered a troubling problem with python.

Wondering if anybody can explain if this is a bug or feature.

array1 = ['a','b','c']
test = array1

del test[2]

print(test)
print(array1)

What would you guess the output is?

It is

['a', 'b']
['a', 'b']

How does the RHS take the value of the left? Thanks,

2 Answers2

1

This is a feature of lists, when you say test= array1 (you are providing an alias to the list), you can reach the desired solution by slicing the list instead.

array1 = ['a','b','c']
test = array1[:]

del test[2]

print(test)
print(array1)
Dhanush Raja
  • 308
  • 1
  • 2
  • 8
1

It is not a bug, it is a very knowable feature of python. If you want to copy a list you have 2 options: option1: you can make a shallow copy of the list by putting the RHS in list() constructor. option2: you can make a deep copy of the list by using the import copy module, and then using the deepcopy method.

Shahryar
  • 324
  • 1
  • 3
  • 17