Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I am using lxml in Python to parse an XML file. The file contains records with elements. The first element is always there. However, the other elements are not always available in each record. If an element is not there I want to add a "None" entry to Elementx list. When I do that each element list has the same size and I can easily append new values in the for loop when these are not present in the previous list. How can i append a "None" value in the element list when the element is not available in the record?

The code looks like this:

Element1_list = []
Element2_list = []
.
.
ElementN_list = []

  def repeat():
    xmlfile = urllib2.urlopen("link.xml").read()
    root = lxml.etree.fromstring(xmlfile)

    # Grabbing the elements from the XML file, list are here not equal in size
    Element1 = root.xpath('//Record/Element1/text()')
    Element2 = root.xpath('//Record/Element2/text()')
    .
    .
    ElementN = root.xpath('//Record/ElementN/text()')

    i = 0
    for element in Element1: 
      if element not in Element1_list: 
        Element1_list.append(Element1[i])
        Element2_list.append(Element2[i])
        .
        .
        ElementN_list.append(ElementN[i])
    i = i + 1
  repeat()

repeat()

Thanks in advance.

share|improve this question

1 Answer 1

you can try to use if else.

lst = []
ele1,ele2 = None,'Something'
lst.append( ele1 if ele1 else None )
lst.append( ele2 if ele2 else None )
print lst 
[None, 'Something']
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.