Hunsu
Hunsu

Reputation: 3381

Reference in Python

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.

Upvotes: 0

Views: 63

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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)

Upvotes: 3

Savir
Savir

Reputation: 18418

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)

Upvotes: 1

Related Questions