Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unexpected (to me) behaviour when deleting lists

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

  • add each relevant chunk to list1, append list1 to final_list. (for easy and neat future presentation)
  • For next relevant piece of information I'm deleting the "old" information in list1 with *list1[:] = []
  • append the new fresh information to list1, append list1 to final_list and voilà... I thought :)

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)]
like image 989
Fredrik Avatar asked May 14 '26 14:05

Fredrik


1 Answers

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.

like image 149
drali Avatar answered May 17 '26 02:05

drali