Confusing [...] List in Python: What is it?

Solution 1:

It can also appear if you have a circular structure with a list pointing to itself. Like this:

>>> a = [1,2]
>>> a.append(a)
>>> a
[1, 2, [...]]
>>> 

Since python can't print out the structure (it would be an infinite loop) it uses the ellipsis to show that there is recursion in the structure.


I'm not quite sure if the question was what what going on or how to fix it, but I'll try to correct the functions above.

In both of them, you first make two recursive calls, which add data to the list y, and then AGAIN append the returned data to y. This means the same data will be present several times in the result.

Either just collect all the data without adding to any y, with something like

return [x[2]]+keys(x[0])+keys(x[1])

or just do the appending in the calls, with something like

y += [x[2]]
keys(x[0], y) #Add left children to y...
keys(x[1], y) #Add right children to y...
return y

(Of course, both these snippets need handling for empty lists etc)

@Abgan also noted that you really don't want y=[] in the initializer.

Solution 2:

I believe, that your 'tree' contains itself, therefore it contains cycles.

Try this code:

   a = [1,2,3,4]
   print a
   a.append(a)
   print a

The first print outputs:

  [1,2,3,4]

while the second:

  [1,2,3,4, [...]]
 

The reason is using

 def Keys(x,y=[]):
 
This is wrong and evil. List is a mutable object, and when used as a default parameter, it is preserved between function calls. So each y += "anything" operation adds to the same list (in all function calls, and since the function is recursive...)

See the Effbot or Devshed for more details on mutable objects passed as default values for functions.