0

I have this code :

doc = parse('sites.xml')
sites = []
for item in doc.documentElement.getElementsByTagName("site"):
    try:
        site = Site()
        site.name = item.getElementsByTagName("name")[0].childNodes[0].nodeValue
        site.start = item.getElementsByTagName("start")[0].childNodes[0].nodeValue
        site.end = item.getElementsByTagName("end")[0].childNodes[0].nodeValue
        site.Id = item.getElementsByTagName("id")[0].childNodes[0].nodeValue
        sites.append(site)
    except:
        pass
for l in range(len(sites)):
    print(site.name + ' ' + site.start + ' ' + site.end + ' ' + site.Id)

I got the last line repeated on output. I don't know why the value of site has changed. Normally at every iteration I create a new reference.

0

2 Answers 2

3

You are iterating len(sites) times, but never assign anything to site; it is still bound to the last value bound in the previous loop.

Just loop over sites directly:

for site in sites:
    print(site.name + ' ' + site.start + ' ' + site.end + ' ' + site.Id)

Using a range(len(sites)) loop is still possible, albeit un-pythonic and needlessly verbose; you'd have to use the generated index to bind site each loop iteration with:

for l in range(len(sites)):
    site = sites[l]
    print(site.name + ' ' + site.start + ' ' + site.end + ' ' + site.Id)
Sign up to request clarification or add additional context in comments.

Comments

1

In your second for loop (for l in range...) you're not getting the site instance. You're getting an index and storing it in l (which gives you an int), but you're never using that index to retrieve the site instance from the sites list so the variable site is still pointing to the last site created on your first for loop.

Try:

for l in range(len(sites)):
    site=sites[l]
    print(site.name + ' ' + site.start + ' ' + site.end + ' ' + site.Id)

or even better

for site in sites:
    print(site.name + ' ' + site.start + ' ' + site.end + ' ' + site.Id)

Comments

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.