Split list into smaller lists (split in half)
⚡TLDR
Chop a list into two using integer division and list slicing:
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:
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:
Your pizza slicing function
A reusable function can handle different party sizes:
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).
Linked
Linked
Was this article helpful?