0

I was writing some Python 3.2 code and this question came to me:

I've got these variables:

# a list of xml.dom nodes (this is just an example!)
child_nodes = [node1, node2, node3]
# I want to add every item in child_node into this node (this also a xml.dom Node)
parent = xml_document.createElement('TheParentNode')

This is exactly what I want to do:

for node in child_nodes:
    if node is not None:
        parent.appendChild(node)

I wrote it in one line like this:

[parent.appendChild(c) for c in child_nodes if c is not None]

I'm not going to use the list result at all, I only need the appendChild to do its work.

I'm not a very experienced python programmer, so I wonder which one is better? I like the single line solution, but I would like to know from experienced python programmers:

Which one is better, in a context of either code beauty/maintainability) and performance/memory use.

0

2 Answers 2

8

The former is preferable in this situation.

The latter is called a list comprehension and creates a new list object full of the results of each call to parent.appendChild(c). And then discards it.

However, if you want to make a list based on this kind of iteration, then you should certainly employ a list comprehension.

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

Comments

0

The question of code beauty/maintainability is a tricky one. It's really up to you and whoever you work with to decide.

For a long time I was uncomfortable with list comprehensions and so on and preferred writing it the first way because it was easier for me to read. Some people I work with, however, prefer the second method.

1 Comment

Not if it only uses the side effects.

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.