0

For example, we can't manually enter in the list:

list = [<element1>, <element2>, <element3>...]

which throws an error:

>>> list = [<DOM Text node "u'\n\t'">]
  File "<stdin>", line 1
    list = [<DOM Text node "u'\n\t'">]
        ^
SyntaxError: invalid syntax

whereas we can put the element from the XML parse elements into a list, which doesn't cause any syntax error. I have listed some XML elements in a list:

[<DOM Text node "u'\n\t'">, 
 <DOM Element: APPLE at 0x18a4648>, 
 <DOM Text node "u'\n\t\n\t'">, 
 <DOM Element: GOOGLE at 0x18a4968>, 
 <DOM Text node "u'\n\t\n\t'">, 
 <DOM Element: LENOVO at 0x18a4b48>, 
 <DOM Text node "u'\n\t\n\t'">, 
 <DOM Element: SAMSUNG at 0x18a4be8>, 
 <DOM Text node "u '\n'">]

which works fine, but when I manually try to feed the list with above elements, it fails.

Can anyone explain why this is so?

Sharath K
  • 55
  • 7
  • 1
    `` is the *representation* of the node, `node.__repr__()`, it is **not** the same thing as the actual node object, which doesn't have a "literal" representation. The representation is not, in itself, valid Python syntax; hence the `SyntaxError`. – jonrsharpe Nov 27 '14 at 11:43
  • You can put any Python object into a list. An XML parse element is a python object, what you have is invalid syntax. You maybe want to create a string object instead. – cdarke Nov 27 '14 at 12:04

1 Answers1

0

Whatever is printed between the angled brackets is simply a human-readable presentation of a class, for example:

>>> class Test:
...  pass
... 
>>> a = Test()
>>> print(a)
<__main__.Test object at 0x7f76070b6198>
>>> repr(a)
'<__main__.Test object at 0x7f76070b6198>'

the <...> is just a string of text, we can actually control what it printed with the __str__() and __repr__() functions:

>>> class Banana:
...   def __str__(self):
...     return 'I am probably yellow!'
...
...   def __repr__(self):
...     return 'I am probably yellow!'
... 
>>> b = Banana()
>>> print(b)
I am probably yellow!
>>> repr(b)
I am probably yellow!

If you want to create a list with these variables, then use the variable names (in this case, a & b): list = [a, b]

Bonus hint:
list is a builtin name in Python (refering to the list type (type([]) == list); you probably don't want to use this as a variable or function name (but because Python is cool, it will allow you to do so anyway).

Community
  • 1
  • 1
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146