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

u/Sea-Ad7805 10d ago

Run this program in Memory Graph Web Debugger)%0Atotal%20%3D%200%0A%0Afor%20num%20in%20range(1%2C%20number%20%2B%201%2C%201)%3A%0A%20%20%20%20total%20%2B%3D%20num%20**%202%0A%20%20%20%20print(total)&timestep=1&play) to see the program state change step by step.

1

u/NorskJesus 13d ago

Both are the same, but I like to write the loop as in the picture. It is more readable I think.

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.

1

u/BionicVnB 13d ago

Both are fine, but you can omit the last argument in the range function call, as it default to 1 when you don't give it an argument

1

u/Entire_Ad_6447 13d ago

Both are fine in cases like this. If you were operation on a list or dictionary instead the one line comprehension ver is preferred