Python List slicing

Hey so im working on this question on slicing the middle of a list. I wanted to know if there is a dynamic way to getting the middle of a list. I personally just counted the list and subtracted an equal amount on both ends to get the middle. but I could imagine if I had a list that thousands or millions of indexes long I probably wouldn’t be able to do that.

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-lists/lessons/use-python-list/exercises/slice-iii

suitcase = ['shirt', 'shirt', 'pants', 'pants', 'pajamas', 'books']

beginning = suitcase[0:4]

print(beginning)

middle = suitcase[2:4]

print(middle)

Here are some concepts to think about to solve it the way you are suggesting:

  1. You can get the total number of items from a list with len()
  2. You can use // to do floor division on any number and always get an integer
  3. You can slice lists with the colon notation, keeping in mind that [start:finish] where start will be included in the slice but finish will not.

I bet you can think of a way to do it now! :wink:

1 Like