Python list comprehension vs. nested loop, conciseness/efficiency
<p>The following 2 methods do the same thing. Which one is more efficient in terms of time/space complexity?</p>

<pre><code>** Method A**
for student in group.students:
    for grade in student.grades:
        some_operation(grade)

** Method B**
for grade in [grade for student in group.students for grade in student.grades]
    some_operation(grade)
</code></pre>

<p>Method B looks weird and redundant. You could shorten it to:</p>

<pre><code>[some_operation(grade) for student in group.students for grade in student.grades]
</code></pre>

<p>But method A is better either way because it doesn't create a list. Making a list simply to throw it away is confusing to the reader and wastes memory.</p>

python code-complexity