How do I split a list into equally-sized chunks?

Here’s a generator that yields evenly-sized chunks: def chunks(lst, n): “””Yield successive n-sized chunks from lst.””” for i in range(0, len(lst), n): yield lst[i:i + n] import pprint pprint.pprint(list(chunks(range(10, 75), 10))) [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, … Read more

How do I clone a list so that it doesn’t change unexpectedly after assignment?

new_list = my_list doesn’t actually create a second list. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment. To actually copy the list, you have several options: You can use the builtin list.copy() method (available since Python 3.3): … Read more