1

I've created a list in python,

 list1 = [1,2,3,4]

and tried to append it tp itself,

 list1.append(list1)

this is what i've got, it's kind of never ending! could someone please explain me what is happening?

 >>> list1=[1,2,3,4]
 >>> list1.append(list1)
 >>> list1
     [1, 2, 3, 4, [...]]
 >>> len(list1)
     5
 >>> len(list1[4])
     5
 >>> print list1[4]
     [1, 2, 3, 4, [...]]
 >>> print list1[4][4]
     [1, 2, 3, 4, [...]]
 >>> print list1[4][4][4]
     [1, 2, 3, 4, [...]]
 >>> print list1[4][4][4][4]
     [1, 2, 3, 4, [...]]
 >>> print list1[4][4][4][4][4]
     [1, 2, 3, 4, [...]]
 >>> print list1[4][4][4][4][4][4]
     [1, 2, 3, 4, [...]]
 >>> print list1[4][4][4][4][4][4][4]
     [1, 2, 3, 4, [...]]
 >>> print list1[4][4][4][4][4][4][4][4]
     [1, 2, 3, 4, [...]]
 >>> print list1[4][4][4][4][4][4][4][4][4]
     [1, 2, 3, 4, [...]]

that's never ending. Thank You

Bujjigadu
  • 11
  • 2
  • @alko, I dont know that's referred as Circular reference ! But my question is not about [...] ! – Bujjigadu Dec 07 '13 at 14:08
  • dear editors, kindly check the question before editing, my question is not about what is [...] , the question is why ? why is this happening?. Thank You – Bujjigadu Dec 07 '13 at 14:11

1 Answers1

1

Names in Python are pointers to objects. In this case

>>> lst = [1, 2, 3, 4]

you create a new list object with 4 int values in, and assign that to the name lst. Next

>>> lst.append(lst)

you add a new item to the end of your list; a pointer to the list itself. This creates the circular reference, that Python prints as [...]. This is because the last item in lst points to lst, in which the last item points to lst, in which...

If you want to append the content of the list to your list, you need to copy the object, which you can do with a slice:

>>> lst.append(lst[:])
>>> lst
[1, 2, 3, 4, [1, 2, 3, 4]]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Another way append the contents of the list to itself is with `lst.extend(lst)` which would result in `lst` becoming `[1, 2, 3, 4, 1, 2, 3, 4]` which I suspect is what the OP wants to happen. – martineau Dec 07 '13 at 14:45