Lists are a useful concept in Python and in many ways are similar to arrays in other programming languages. Python provides a number of list methods which allow you to manipulate the elements within and these are documented in the official data structures documentation.
One thing I needed to do recently was to take a list of data and split it into a number of smaller chunks. I wanted to specify the number of the chunks and the elements of the list to be split appropriately,
In the example below the function “get_chunks” is defined. It accepts two arguments. The first is a list of data and the second is the number of chunks you require.
#!/usr/bin/env python def main(): # Create an example list full of numbers MyList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] # Print the result of passing the list to the # function get_chunks with a value of 4 print get_chunks(MyList,4) def get_chunks(MyList, n): # Declare some empty lists chunk =  chunks =  # Step through the data n elements # at a time for x in range(0, len(MyList), n): # Extract n elements chunk = MyList[x:x+n] # Add them to list chunks.append(chunk) # Return the new list return chunks # Run main function main()
The function returns a list that contains the chunks as elements. The print statement then prints the resulting list of chunks to screen. You can also populate a new list with the result of “get_chunks” and then handle chunks individually :
NewList = get_chunks(MyList,4) # Print first chunk print NewList # Print 4th chunk print NewList
The following code is a compact version of “get_chunks”. It performs the same process but is much shorter.
def get_chunks2(MyList, n): return [MyList[x:x+n] for x in range(0, len(MyList), n)]