Explain Codes LogoExplain Codes Logo

Split list into smaller lists (split in half)

python
list-slicing
generators
performance-optimization
Alex KataevbyAlex Kataev·Mar 7, 2025
TLDR

Chop a list into two using integer division and list slicing:

lst = [1, 2, 3, 4, 5, 6] half = len(lst) // 2 # Split at midway, no need to play "eeny, meeny, miny, moe" halves = lst[:half], lst[half:]

Access it like halves[0] for the first half and halves[1] for the second half. Yes, you don't need a chainsaw for slicing lists!

No panic for odd-sized lists, Python slicing slays it by including the extra element in the second sublist. Python got your back!

More than half: smaller equally distributed slices

When you want to share your pizza with more friends, distribute equally into 3 slices each:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] slice_size = 3 slices = [lst[i:i + slice_size] for i in range(0, len(lst), slice_size)]

Tap-dancing through the list: slicing with step

To pick every second slice of pizza from the box or every third, Python has a step feature in slicing:

step2 = lst[::2] # Picks every 2nd slice, starting from the first step3 = lst[::3] # Picks every 3rd slice, starting from the first

Your pizza slicing function

A reusable function can handle different party sizes:

def pizza_slices(pizza, slice_size): return [pizza[i:i + slice_size] for i in range(0, len(pizza), slice_size)]

Now, just say pizza_slices(lst, 3) to get sublists of 3 elements each. The party gets simplified!

Be aware when slicing

While slicing is your friend, here are some friendly reminders:

  • Index Errors: Slicing doesn't throw tantrums if you go out of bounds. But, expect an empty slice in return! Pay attention to your indices.
  • Sharing is caring: Slicing shares a shallow copy, keeping a reference to the same objects for nested objects within the list.
  • Big party considerations: Slicing a large pizza (or list) could result in slower service (or performance). Generators can help serve large parties (or datasets).