0

I am new to python and learning to read in xml files. Running my code to append the items gives me repeated arrays. I guess it is looping through all the items appending and returning an array each time. I just want one array the array of all the items. What am I doing wrong?

The code is as follows:

countries_im = []
for country in root.findall('./country'):
        data = {
            'name': None,
            'infant_mortality': None
        }
        data['name'] = country.find('./name').text
        data['infant_mortality'] = country.findtext('./infant_mortality')
        if data['infant_mortality'] is not None:
            countries_im.append(data['infant_mortality'])
            print(countries_im)

The result is as follows:

['13.19']
['13.19', '4.78']
['13.19', '4.78', '7.9']
['13.19', '4.78', '7.9', '6.16']
['13.19', '4.78', '7.9', '6.16', '3.69']
['13.19', '4.78', '7.9', '6.16', '3.69', '3.31']

I just want the last array. Thanks for the help

1
  • 1
    You are printing the array at each step of the for-loop. Move the print statement outside the for-loop. Commented Mar 10, 2017 at 20:17

2 Answers 2

2

Your code is not returning multiple lists. In fact, it is not returning anything. You have only one existing list that is changing it's content via append.

The result you are showing is the output of calling print(countries_im) each time you append an item to the list.

If you change your code to this:

countries_im = []
for country in root.findall('./country'):
        data = {
            'name': None,
            'infant_mortality': None
        }
        data['name'] = country.find('./name').text
        data['infant_mortality'] = country.findtext('./infant_mortality')
        if data['infant_mortality'] is not None:
            countries_im.append(data['infant_mortality'])
print(countries_im)

You will se that the list that you have in memory have all the items appended.

Sign up to request clarification or add additional context in comments.

Comments

1

If I am understanding correctly, your code is correct, you just need to move the print statement outside of the for loop. In other words, you are printing the same array each time you add something. So, you are ending up with what you want at the end of the for loop (the completed array).

2 Comments

You are correct. How do I move the print statement outside the loop so that I could print only the last final array?
Sorry for the delay, please see the answer from @david-de-la-iglesia it is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.