0

I created a code for picking random musics in a list of musics (music_list) and adding them to music_queue. When I execute this code, all the elements of music_list are deleted and I don't understand why.

print("Music list lenght : " + str(len(music_list)))
if len(music_queue) == 0:
    tmp = music_list
    while len(tmp) > 0:
        music_queue.append(tmp.pop(randint(0,len(tmp) - 1)))
print("Music list lenght : " + str(len(music_list)))
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Redover
  • 13
  • 3
  • Does this answer your question? [python: changes to my copy variable affect the original variable](https://stackoverflow.com/questions/19951816/python-changes-to-my-copy-variable-affect-the-original-variable) or better yet, the duplicate from that question: https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent – Tomerikoo Nov 25 '20 at 18:13
  • try ```tmp = music_list.copy()``` instead. For lists, the "=" operator makes a copy of the same object, and so edits the original when you edit the copy. – William Baker Morrison Nov 25 '20 at 18:23

1 Answers1

5

You need to change

tmp = music_list

to

tmp = music_list[:]

setting tmp to music list without copying, making a change to one will edit both lists.

This is assuming you don't want to edit music_list

The reason of this is because without copying you are referencing the same item in memory:

Without copying:

tmp = music_list

Memory locations:

>>> id(music_list)   
2614314102592
>>> id(tmp)          
2614314102592

With copying:

tmp = music_list[:]

Memory locations:

>>> id(music_list)
1782888775808
>>> id(tmp)
1782888775744
difurious
  • 1,523
  • 3
  • 19
  • 32