1

I got a list with 958 elements.

myList = [1, 2, 3, 4, ..., 958]

I want to take first 100 elements, then next 100 (from 100 to 200) and so on.

What I have tried:

sum = 0
ct = 0
for i in range(len(myList):
   sum = sum + myList[i]
   ct = ct + 1
   if ct == 100:
      ct = 0 
      print(sum)
      sum = 0

It works good until the 900th element. Then it cannot do the sum of the last 58 elements of myList because the ct will not get 100.

Any ideas?

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
Paul Viorel
  • 234
  • 1
  • 11
  • 1
    You only print a sum when you get to a multiple of 100. So you never print the sum of the last 58 elements. – Barmar Apr 01 '22 at 16:37
  • 2
    You're not summing the list elements, you're summing the indexes. Use `for i in myList:` to sum the elements. – Barmar Apr 01 '22 at 16:38
  • You're also using `ct` effectively to duplicate the value of `i`. If you follow @Barmar s advice consider using enumerate as well: `for i, n in enumerate(myList):` – joshmeranda Apr 01 '22 at 16:39
  • Where's the `50 x 50` elements list? – accdias Apr 01 '22 at 16:39
  • @Barmar I fixed with ```myList[i]```. – Paul Viorel Apr 01 '22 at 16:41
  • Your example does not work, I can assure you it gives a SyntaxError. Moreover, what do you want to do exactly ? Your title doesn't fit wih your description and your code does totally something other. – imperosol Apr 01 '22 at 16:41
  • Don't tag both `python-3.x` and `python-2.7` - they literally both say only tag when it matters which one it is. Also, don't name variables the same as builtins (like `sum`). Finally, why is the title saying "50 by 50 elements"? You're going through the list by 100s, and the list isn't 2d... – kenntnisse Apr 01 '22 at 16:43
  • One would normally use slicing and the built-in *sum()* function for this but you have overridden *sum*. It's rarely a good idea to override built-in functions – DarkKnight Apr 01 '22 at 16:44
  • This seems to be a duplicate of https://stackoverflow.com/questions/434287/how-to-iterate-over-a-list-in-chunks – The Matt Jan 01 '23 at 19:37
  • Does this answer your question? [How to iterate over a list in chunks](https://stackoverflow.com/questions/434287/how-to-iterate-over-a-list-in-chunks) – The Matt Jan 01 '23 at 19:37

7 Answers7

3

Step through the list 100 at a time and sum the slice. Slicing beyond the end of a list is handled correctly:

myList = list(range(1,959))

for i in range(0,len(myList),100):
    sub = myList[i:i+100]
    print(f'sum of {sub[0]}..{sub[-1]} is {sum(sub)}')

Output:

sum of 1..100 is 5050
sum of 101..200 is 15050
sum of 201..300 is 25050
sum of 301..400 is 35050
sum of 401..500 is 45050
sum of 501..600 is 55050
sum of 601..700 is 65050
sum of 701..800 is 75050
sum of 801..900 is 85050
sum of 901..958 is 53911
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
2

Since you only print the sum when you get to a multiple of 100, you never print the sum of the last group of elements, since it's not 100 elements. To get the last group, print the sum after the loop ends.

You can also use enumerate() to get an index directly in the loop, rather than incrementing your own ct variable.

total = 0
for i, item in enumerate(myList, 1):
    total += item
    if i % 100 == 0:
        print(total)
        total = 0
# Print the final group
if i % 100 != 0:
    print(total)

I also renamed the sum variable to total, because sum is the name of a built-in function.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

From the itertools module's documentation:

from itertools import zip_longest


def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
    "Collect data into non-overlapping fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
    # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
    # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
    args = [iter(iterable)] * n
    if incomplete == 'fill':
        return zip_longest(*args, fillvalue=fillvalue)
    if incomplete == 'strict':
        return zip(*args, strict=True)
    if incomplete == 'ignore':
        return zip(*args)
    else:
        raise ValueError('Expected fill, strict, or ignore')


for century in grouper(myList, 100, fillvalue=0):
    print(sum(century))
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can just slice the list as follows:

for k in range(0, len(mylist), 100):
  print(sum(mylist[k:k+100]))

This will print the sum of elements in groups of 100. If the list length is not an exact multiple of 100, the last sum will be that of the remaining elements

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

Try the following:

index = 1
slicesize = 100

start = 0
end = 100

myList = range(1, 958)

while True:
    myslice = myList[start:end]
    
    index += 1
    start = end
    end = index * slicesize
    if start > len(myList):
        break
Adeeb
  • 1,271
  • 3
  • 16
  • 33
0

I believe that this should do the trick.

import random

# generate list with N elements, each of which is a random integer in [0, 99]
N = 57
random.seed()
myList = [random.randint(0, 99) for i in range(0, N)]

# Calculate total number of prints before there will be less than num_elem
# elements remaining in the list.
num_elem = 10
total_prints = len(myList) // num_elem

for i in range(0, total_prints):
    index = i * num_elem
    print(sum(myList[index:index + num_elem]))

# if there are remaining elements, print their sum
if (len(myList) % num_elem) != 0:
    print(sum(myList[index + num_elem:]))
OTheDev
  • 2,916
  • 2
  • 4
  • 20
0
def n_elements_per_call(iterable, n=100):
    buffer = []
    for i in iterable:
        buffer.append(i)
        if len(buffer) < n:
            continue
        yield buffer
        buffer.clear()
    if buffer:
        yield buffer

my_list = list(range(959))
for nums in n_elements_per_call(my_list):
    print(nums)

qwerty_url
  • 535
  • 4
  • 12