Hey. In the loop I generate objects and write them into the response variable. The specified variable is added to the list. I will give an example:

 answer = [] for query in listOfLogs: response = {} response = Request(query) elem = {"response": response, "query": query, 'isNull': False} answer.append(elem) for item1 in answer: print item1 print "###" 

As a result, for some reason, the list contains references to the response, and with each new creation of the response object, the Request function overwrites all elements of the list. I would like to copy the object to the list, and not to add it by reference. I will give an example of the log:

  Луговая Рыбачье ### Луговая (эксп.) Рыбачье Луговая (эксп.) Рыбачье ### ЛуговаяРыбачье ЛуговаяРыбачье ЛуговаяРыбачье ### Ногинск, Горьковское шоссе, 56 км, дом 1 Ногинск, Горьковское шоссе, 56 км, дом 1 Ногинск, Горьковское шоссе, 56 км, дом 1 Ногинск, Горьковское шоссе, 56 км, дом 1 ### 

Tell me how to do this?

  • one
    How does the Request() function work? And where is the answer list? - kitscribe
  • What content do you have in listOfLogs? - codename0082016
  • @ codename0082016 the contents are not important here - kitscribe
  • one
    The code in question can not show the output to generate any input. Try to create a minimal but complete example of the code that shows the problem and provide the output corresponding to this code. The minimum reproducible example is jfs
  • @KitScribe, what's the difference, how does Request() ? String handles. The story about the answer corrected - hedgehogues

1 answer 1

In python, much is transmitted by reference. In order to transfer not by reference, you need to explicitly copy the object with the "specially trained for this function" deepcopy from the copy package:

 import copy answer = [] for query in listOfLogs: response = {} response = Request(query) elem = {"response": copy.deepcopy(response), "query": copy.deepcopy(query), 'isNull': False} answer.append(elem) for item1 in answer: print item1 print "###" 

I note that there are two similar functions in python: copy and deepcopy . deepcopy makes a full copy, and copy - a superficial (not in the usual sense). An example of their use and differences can be found here.