I am using Django to build a site mainly to learn something about websie building.And I came across something I thought is strange.I have this code below:
all_words=Word.objects.all()[0:100]
user=request.user
wordlist = []
//wordinfo = {} --->This doesn't work
for word in all_words:
wordinfo = {}//This works fine
taged_word = FlagWord.objects.filter(word = word,user = user)
if taged_word :
wordinfo['usertag'] = True
else:
wordinfo['usertag'] = False
wordinfo['word'] = word
wordlist.append(wordinfo)
Notice where the wordinfo is placed.I think both would work because the latter content would replace the previous one anyway.But when it’s placed outside the for loop,I would get 100 elements in the wordlist which are all the same.The word property would all be the last word in all_words.
I know if the wordinfo is placed in the for loop,a new wordinfo would be created.But question is I think if it’s placed outside the for loop,it should also work.Can somebody explain to me what’s the difference?Why can’t it be placed outside the for loop?
in python variables reference objects. so when wordinfo is outside of the loop the values it contains are referenced by your list of values.
This means that on your last itearation all the values in wordlist will be equal to the last value assigned to
wordinfoso at the end of the loop you will have
if wordinfo is eaual to
{'usertag': True, 'word': 'because'}all the items in the list will have that value.you could further refactor this to look something like: