Home > Blockchain >  for-loop error : "Output exceeds the size limit." (VSCode)
for-loop error : "Output exceeds the size limit." (VSCode)

Time:01-23

I was trying to make a for loop to sum the integers from 1 to 100 in Python and wrote the code like this :

for i in range(1, 101) :
    sum_list = []
    sum_list.append(i)
    print(sum(sum_list))

but it didn't print the output I wanted (5050) and the VSCode python interpreter showed the message that output exceeded the size limit.

I want to know what causes this error and what I should do if I want to get the correct output.

CodePudding user response:

You’re not getting the output you expect (5050) because the list needs to be initialized before you begin iterating through integers.

For example:

sum_list = []

for i in range(1, 101):
    sum_list.append(i)

print(sum(sum_list))

As far as the error goes, it seems to be a visual code extension’s config. It’s likely due to you printing out the sum of every iteration. I found a similar question on stackoverflow, perhaps the answer could help you as well. I’d recommend checking your VSCode / extension settings.

CodePudding user response:

I'm not sure why you're getting a size limit exception, those only occur when you want to output some very large data (and i think in a jupyter notebook). but for starters I would move the sum_list creation out of the for loop.

sum_list = []
for i in range(1, 101):
    sum_list.append(i)
    print(sum(sum_list))

This worked for me, but I didn't get your error when i ran your code, so

CodePudding user response:

You were not getting the result because you were initializing the list inside the for loop. You need to initialize in the beginning before starting for loop.

sum_list = []
for i in range(1, 101):
    sum_list.append(i)

print(sum(sum_list))
#5050

2.You can get the result my list comprehension as well.

sum_list=[i for i in range(1,101)]
print(sum(sum_list))
#5050

3.another way:

sum_list=list(range(1,101))
print(sum(sum_list))
#5050

4.Directly sum generator expression:

sum(i for i in range(1,101))
#5050
  • Related