1

I have an array of ~1,000 integers which I want to iterate 50 items at a time and append to a string. I am not quite sure how to go about this in Python.

mystring = ""
for [every 50 items] in arr:
    string += 50 items
    print(string)
MR MDOX
  • 35
  • 4

2 Answers2

4

You can split the list into slices to iterate over.

l = [ ... ]
for x in (l[i:i + 50] for i in range(0, len(l), 50)):
    print(x)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1
def chunks(arr: list, n: int) -> Generator:
    """
    Yield successive n-sized chunks from arr.
    :param arr
    :param n
    :return generator
    """
    for i in range(0, len(arr), n):
        yield arr[i:i + n]

you can use this function to create n-sized chunks from a array
for example:

list(chunks([1, 2, 3, 4], 2)) # => [[1,2],[3,4]]
in your case you can pass your array to function and pass 50 to second argument
after that do for loop on result of chunks function

Dharman
  • 30,962
  • 25
  • 85
  • 135
Aazerra
  • 161
  • 9