I noticed something very weird. I tried to look at where it was going wrong and realised that for some reason, the nest[0]
list keeps changing midway through the loop.
>>> nest = [['prefix'],['line 1'],['line 2']]
>>> for part in nest[1:]:
... list = nest[0]
... list += part
... print list
The output that I get is:
['prefix', 'line 1']
['prefix', 'line 1', 'line 2']
Whereas, what I need is:
['prefix', 'line 1']
['prefix', 'line 2']
Can somebody explain why this happens? I might be doing something very stupid.
EDIT: with explanation of pointers, as requested
Your problem is that when you assign list to nest[0], you are not creating a new list, your just assigning a pointer. Your pointer is directed to the list containing ['prefix']
On your first iteration, you add something to this list
On your second iteration, you don't make a NEW list, you just repoint to the old one.
Then when you append again, you're appending to the old list!
What you mean is:
nest = [['prefix'],['line 1'],['line 2']]
for part in nest[1:]:
list = [] + nest[0]
list += part
print list
There's several ways to think about this. Here's one. Say you had a deck of cards object:
myobj = Deck().
If I then say,
myobj2 = myobj,
I haven't created a new deck of cards, it would be like someone else looking at the deck I already have. We need to be able to do that to do a lot of programming (it's the fundamentals of object oriented design)! I would need to say
myobj3 = Deck()
to construct a new deck of cards object.
Consider:
myobj.shuffle #we're shuffling one deck, that two people are looking at
Both myobj and myobj2 will change. Calling myobj3.shuffle leaves the other two untouched. What you've done told someone to re-look at the same deck, where you meant to make a new one!
list = nest[0]
mean you assign pointer to nest[0] to variable name list
If you want your expected output, you need to create a new list to make sure it will not effect the original.
nest = [['prefix'],['line 1'],['line 2']]
for part in nest[1:]:
list = nest[0] + part
print list
nest[0] + part
will create a new value and assign to list
this is just clarification in simple words :
the wrong
'list += part'
in
' for part in nest[1:]:
list = nest[0]
list += part
print list'
the variable list will change its value in each iteration .. I mean the varible list will assigned to the following values :
list = ['prefix'] then after the first iteration it will reassigned to be :
list = ['prefix' , 'line 1'] ## note the loop excute list +=part , if you continue it will get all members of [nest]
so the solution focus on gitting seperate variable which keep its value constant in each iteration
'list = [] + nest[0]'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.