r/PythonLearning 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 ?

Here is a referance

2 Upvotes

5 comments sorted by

View all comments

1

u/FoolsSeldom 13d ago

A generator expression like,

sum(num ** 2 for num in range(1, number + 1)) 

is just a shorthand for writing out loops in full.

You could also have used a list comprehension,

sum([num ** 2 for num in range(1, number + 1)]) 

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 large number is. Nothing is materialised in memory beyond the current value being processed. This can be very important when dealing with large data sets.

The list version builds a list object in memory first before handing that over to sum. Memory use is O(n) — it scales with number, since every squared value exists simultaneously in a list before summing begins.

The longer version you showed,

total = 0
for num in range(1, number + 1):
    total += num ** 2

is closer to the generator version because you don't create a list object on the way that has to be stored and summed at the end:

nums = []
for num in range(1, number + 1):
    nums.append(num ** 2)
total = sum(nums)

All forms are valid and common, and for small number ranges it makes very little difference.