Reputation: 73
for example,i got a list:
mylist = [1,2,3]
we all know append() can add a new item at the end of the list like that:
mylist.append(4)
now the mylist is [1,2,3,4]
my issue is what happened when mylist append itself????
mylist.append(mylist)
at first i think it will look like this:
[1,2,3,4,[1,2,3,4]]
but when i print it, output is [1,2,3,4,[...]],so i print the mylist[5] and it's same to the mylist:[1,2,3,4,[...]]
so you can loop the last item of list endless,and the last item always be the same to original mylist!!!!!
anyone can tell me why is that????????
Upvotes: 0
Views: 699
Reputation: 5193
It's doing that because you're telling Python to append a list(my_list
) to a list. If you want to extend the list with the contents of the list, you can do this:
new_list = old_list + new_list
output: [1, 2, 3, 4, 1, 2, 3, 4]
or you can use the extend
method.
old_list.extend(my_list)
Which will modify the old_list in place.
Upvotes: 0
Reputation: 168616
Because you aren't appending a copy of the list, but the actual list object itself. Consider this program:
mylist = [1,2,3,4]
mylist.append(mylist)
assert id(mylist) == id(mylist[4])
The final item of the list is a reference to the list itself, so you have a fully recursive, self-referential data structure.
If you want the result [1,2,3,4,[1,2,3,4]]
, then you need to append a copy of the original list, like so:
mylist = [1,2,3,4]
mylist.append(list(mylist))
assert mylist == [1,2,3,4,[1,2,3,4]]
Upvotes: 1