1

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)
3
  • 1
    B: consumes more memory because it builds an intermediate list. Use a generator expression instead: for grade in (grade ...): some_operation(grade). Commented Sep 29, 2016 at 20:57
  • @Bakuriu, "()" indicate generator? So the list of 'grades' won't be created as we loop thru it? Commented Sep 29, 2016 at 21:03
  • Related threads stackoverflow.com/questions/47789/… stackoverflow.com/questions/19933753/… Commented Sep 29, 2016 at 21:14

2 Answers 2

1

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.

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

11 Comments

Agreed. Just don't like multiple levels of loops, because of my OCD. Any idea how to write concise yet equally efficient code in this case?
I strongly dislike this. list-comprehensions are expressions and should not be used to just calla function on a sequence of values. Besides: it consumes memory. If you have a scenario where you have millions of items on which to perform the action you probably don't want to create a useless list with million of elements.
No, do not shorten method B to a single list comprehension. Method B does not create a new list; the list comprehension creates one that you immediately discard.
Agreed with Alex and @Bakuiu list comprehension is inefficient in space.
@cheng shorter code is not necessarily cleaner or clearer. Always choose to write code that is instantly obvious to a reader rather than trying hard to save lines.
|
0

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.

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.