Search code examples
pythonlistsplitlist-comprehensionchunks

How to run a function in loop over the chunks of a list?


I have a list of length 4700 of type string. First I made the list into equal chunks of size 1500. So now, I've 4 lists.

list_with_chunks = [[a,b,c,...],[f,g,h,....],[x,y,z,...],...,[l,m,n,...]]
new_list = []

def function():
 # dummy function
 return 2*x

I want a function which could use the above function() and pass the first chunk of list_with_chunks and append the result to new_list and then take the second chunk and append the result to new_list from wherever the previous appending stopped due to first chunk and so on until I finish passing all the chunks.

Update: Desired output:

new_list = [2*a, 2*b, 2*c.....,2*z] # all the chunks in just one final list.

Please help, TIA!


Solution

  • Loop over the chunks, use a list comprehension to multiple all the chunk elements, and use extend to append the result to the new list.

    def function(new_list, list_of_lists):
        for l in list_of_lists:
            new_list.extend([2 * x for x in l])
    
    function(new_list, list_with_chunks)
    print(new_list)