Search code examples
pythoncode-complexity

Python list comprehension vs. nested loop, conciseness/efficiency


The following 2 methods do the same thing. Which one is more efficient in terms of time/space complexity?

** 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)

Solution

  • Method B looks weird and redundant. You could shorten it to:

    [some_operation(grade) for student in group.students for grade in student.grades]
    

    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.