DEV Community

loading...

Learning Slice Notation with Python

Justin Bermudez
・1 min read

Slicing is a shortcut when you have a given array or list, and you want only a part of that. Going through a for loop or what not can take more work and slicing will take less lines.

Let's say we want 2-5 only

example:

array = [1, 2, 3, 4, 5, 6]

array[1:5]
=>
[2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

The slicing parameters look like so
[(start here but does not include):(number we end on does include):(optional:how many steps to take)]

The above example does not use the third parameter. If left blank, then the third parameter will default to 1.

We can use it like so

example:

array = [1, 2, 3, 4, 5, 6]

array[2:6:2]
=>
[3, 5]
Enter fullscreen mode Exit fullscreen mode

We ignore the 2 and start at 3, then we take 2 steps to include the 5, then we end there because 6 is not 2 steps from 5.

What if we ignored the first parameter?

array = [1, 2, 3, 4, 5, 6]

array[:3]
=>
[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

We would skip the first parameter of where to start so we start from the beginning and the second parameter tells us where to end, so we include everything up to where we stopped at which was 3 here.

Same idea with omitting the first 2 parameters.
If we skip the first 2 then we would just take those steps from beginning of our input to the end.

array = [1, 2, 3, 4, 5, 6]

array[::2]
=>
[2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app