How can I go through a list 100 elements at a time?

Question:

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?

Asked By: Paul Viorel

||

Answers:

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))
Answered By: chepner

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.

Answered By: Barmar

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
Answered By: Mark Tolonen

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
Answered By: Adeeb

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

Answered By: Fred

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:]))
Answered By: oda
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)

Answered By: qwerty_url
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.