Python code not sure how this works

I am working through the python for everyone section and along side this doing the graded assignments on instructors website py4e.com. I was able to complete the Extracting Data from XML problem. my code:

import urllib.parse, urllib.request, urllib.error
import xml.etree.ElementTree as ET
import ssl
url = 'http://py4e-data.dr-chuck.net/comments_1200730.xml'
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
uh = urllib.request.urlopen(url, context = ctx)
data = uh.read()
tree = ET.fromstring(data)
results = tree.findall('.//count')
->print(sum([int (x.text) for x in results]))

Pointed at is what I have a question about. When the instructor mentioned that we can do something like this, at the end of the tuples section, I didn’t understand how it worked. I still don’t. I know the the [brackets ] is telling sum that its taking a list. I assume that the inital x.text is being used as an assignment before the for statement? I would like to understand how this works, thank you in advance.

That’s a so-called list comprehension in python. It can be read almost naturally - int(x.text) for each element x in results. x is just a variable name, it could be anything.

Written differently, with a normal for loop, it would look something like this:

counts = []
for x in results:
    counts.append(int(x.text))
print(sum(counts))

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.