MR MDOX
MR MDOX

Reputation: 35

Python Iterating n items of array at a time

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)

Upvotes: 1

Views: 1782

Answers (2)

Aazerra
Aazerra

Reputation: 161

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

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89264

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)

Upvotes: 4

Related Questions