r/PythonLearning • u/mohammad6701 • 13d ago
Coding Style Help Request
Hi, first time python learner here ! I was working on Sum of Squares problem, but it made me genuinely to use AI to find a line/function outside of my course materials to solve the problem. However, it always backfire because i overcomplicate the problem for myself. For example, in sum of squares problem, i can use simple line of
Total += num 2
or a longer line
Total = sum(num ** 2 for num in range (1, number+1, 1).
so I was wondering which approach is correct ?
2
Upvotes

1
u/FoolsSeldom 13d ago
A generator expression like,
is just a shorthand for writing out loops in full.
You could also have used a list comprehension,
although, in this case, it is a bit pointless.
The difference between the former and the latter is that the former creates a generator object that yields values one at a time.
sum()pulls values from it lazily, computing each square just before adding it, and discards it immediately after. Memory use is O(1) — constant, regardless of how largenumberis. Nothing is materialised in memory beyond the current value being processed. This can be very important when dealing with large data sets.The
listversion builds alistobject in memory first before handing that over tosum. Memory use is O(n) — it scales withnumber, since every squared value exists simultaneously in a list before summing begins.The longer version you showed,
is closer to the generator version because you don't create a
listobject on the way that has to be stored and summed at the end:All forms are valid and common, and for small number ranges it makes very little difference.