nairware
nairware

Reputation: 3190

Why does this python code not replace deleted list elements?

Here is my code:

for each in range(0, number_of_trials):
  temp_list = source_list
  for i in range(10):
    x = random.randrange(0, len(temp_list))
    board[i] = temp_list[x]
    del temp_list[x]

This code is deleting each element from temp_list, as would be expected. But temp_list is not being reset each time the initial for loop runs, setting it back to source_list. As a result, every delete from temp_list is permanent, lasting for every following iteration of the for loop. How can I avoid this and have temp_list "reset" back to its initial status each time?

Upvotes: 2

Views: 99

Answers (4)

Yugal Jindle
Yugal Jindle

Reputation: 45676

This is because :

temp_list = source_list # Doesn't copies the list, but adds the reference.

So, each iteration you are refreshing the reference only.

To copy the list, you can use the trick [:]. This performs list slicing with nothing sliced and produces a new list exactly same as the list being sliced.

Therefore,

for each in range(0, number_of_trials):
  temp_list = source_list[:]                # Changed
  for i in range(10):
    x = random.randrange(0, len(temp_list))
    board[i] = temp_list[x]
    del temp_list[x]

This should work as expected. :)

Upvotes: 0

vanza
vanza

Reputation: 9903

>>> a = [ 1 ]
>>> b = a
>>> del a[0]
>>> print b
[]

Basically, when you use "=", both variables point to the same object. To make a copy, use the copy module.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798814

Copy the list elements instead of the list reference.

temp_list = source_list[:]

Upvotes: 1

Michael Hoffman
Michael Hoffman

Reputation: 34334

The statement temp_list = source_list does not create a new list. It gives a new name temp_list to an existing list. It doesn't matter what name you use to access the list—any changes made via one name will be visible via another.

Instead, you need to copy the list, like this:

temp_list = source_list[:]

This creates a new list that starts with the same contents as source_list. Now you can change the new list without affecting the original.

Upvotes: 3

Related Questions