cheng
cheng

Reputation: 6696

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)

Upvotes: 1

Views: 1877

Answers (2)

Alex Hall
Alex Hall

Reputation: 36013

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.

Upvotes: 1

Kevin London
Kevin London

Reputation: 4728

These have the same time complexity, O(nm), since it's a loop over another loop. So, the n is group.students, and m is students.grades. Functionally, these should be the same time complexity too since it's iterating over both lists either way.

Upvotes: 0

Related Questions