Skip to content

Instantly share code, notes, and snippets.

@mwrites
Created August 8, 2021 08:09
Show Gist options
  • Save mwrites/63d8c0f63294e5cb6650b1a8cfb782b6 to your computer and use it in GitHub Desktop.
Save mwrites/63d8c0f63294e5cb6650b1a8cfb782b6 to your computer and use it in GitHub Desktop.
Python - Slicing
nums = [1, 2, 3, 4]
# ***********************************
# Slicing
# ***********************************
# Syntax is
# slice(start, stop, step)
nums[0:3] # from idx 0 to idx 3 (exclusive) -> 1, 2, 3
nums[0:0] # nothing since we are starting at 0 but excluding 0 -> []
# To the end shortcut for nums[i:len(nums)]
nums[0:] # from the beginning to the end so same as nums -> 1, 2, 3, 4
nums[1:] # from idx 1 to the end -> 2, 3, 4
# Every two number
# Start to the end.. nums[0::
# And add the step as the third arg!
nums[0::2]
# In reverse
# Syntax needs the -1 at the end, start:stop:step to tell that it is descending
nums[3:0:-1] # from idx 3 to idx 0, but remember second arg it is exclusive so it gives -> # 4, 3, 2
# Can be simplified to where -1 means from last item
nums[-1:0:-1] # but still gives 4, 3, 2 because of the stop arg
# nums[-1:-1:-1] does not work, solution is to omit the stop
nums[-1::-1]
# which can be simplified to
nums[::-1]
# Every two numbers from end to beg
nums[::-2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment