0

I have a for loop that generates strings associated with the number in the numbers list by searching through an XML file.

tree = parse("demo.xml")
root = tree.getroot()

fields = {int(child.attrib["number"]): child.attrib["name"] for child in root}

numbers [1, 4, 5, 8, 9, 45, 78]

for number in numbers:
    print(fields.get(number, f"{number} does not exist in XML"))

so the output is like:

Account
Name
ID
Time

I want to save this output to a list, and separate each text by a comma, so it should save this to a list that should look like:

myList: [Account, Name, ID, Time]

How can I do this?

1
  • MyList format isn't right for string, I mean the items in the list should have quotes around them too Commented Sep 30, 2020 at 10:44

2 Answers 2

1

You can use list comprehension

myList = [fields.get(number, f"{number} does not exist in XML") for number in numbers]
Sign up to request clarification or add additional context in comments.

Comments

1

Create a new empty list before starting the loop and add elements to it inside the loop body.

Replace

for number in numbers:
   print(fields.get(number, f"{number} does not exist in XML"))

with

myList = []
for number in numbers:
    myList.append(fields.get(number, f"{number} does not exist in XML")))

You can then use myList to get the output in the format you like. From your question, it seems you may need one of these

print("myList:", myList)
print("myList: [", ",".join(myList), "]")

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.