Fredrik
Fredrik

Reputation: 63

Python unexpected (to me) behaviour when deleting lists

Bumped into a programming issue that puzzles me a bit. Im parsing data and:

All help appreciated!

Example:

final_list=[]
list1 = [1,2,3,4]
list2 = [5,6,7,8]

final_list.append(list1)
final_list.append(list2)
print final_list

list1[:] = []
print final_list

Example output

[[1, 2, 3, 4], [5, 6, 7, 8]]
[[], [5, 6, 7, 8]]

Sys.version

Python: 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)]

Upvotes: 3

Views: 79

Answers (3)

Fredrik
Fredrik

Reputation: 63

As many community readers pointed out, the objects within final_list are only pointers to the original objects "list1" and "list2". In the end i used the method final_list.append(list(list1)) to store the value of list1 within final_list. (As a copy) After this its safe to reset list1 and repeat the process.

Upvotes: 1

drali
drali

Reputation: 317

By calling list1[:] = [], you change the previous value of all list1 everywhere, even in final_list. To preserve the list1 value in final_list, you should make a copy and append the copy instead of the original list. Some explanations and nice methods for list copying can be found here.

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96266

I'm deleting the "old" information in list1 with *list1[:] = []

So, list1 is going to be the same object you're referencing in final_list.

final_list is simply [list1, list2]. Hence the output.

If you want a fresh object, reassign the variable:

list1 = []

Upvotes: 1

Related Questions