Beginner Python tutorial – 10 – Slicing

Slicing is one of the best features of Python. You can get the same functionality in every other language, but not as easy, cool and elegant as in Python

What’s slicing?

Slicing a Python element returns a sub-set of said element.

Let’s say you have a list like this one:

my_list = [6, 23, 7, 23, 78, 12, 44]

You want only the first 3 values. Or maybe the last one. Or the third to fight value. You can get it easily with Python slicing.

Structure

Let’s say we have the ‘my_list’ list we saw a second ago. To slice it, we do it following this structure:

my_list[start:stop:step]
my_list[0:len(my_list):1] # Default values used by python unless specified otherwise

Start, stop and step (this one is optional) are integer values marking the start, stop and the step of said list. When we omit ‘start’, we assume that start equals ‘0’, ‘stop’ is the total length and ‘step’ is ‘1’. Let’s see some examples.

Slicing examples

my_list = [6, 23, 7, 23, 78, 12, 44]

# We want the first 4 values (from 0 to 3)
my_list[0:4] # Returns [6, 23, 7, 23]
my_list[:4] # Also returns [6, 23, 7, 23]

# We want the last 2 values (6 and 7 positions)
my_list[5:7] # Returns [12, 44]
my_list[5:] # Also returns [12, 44]

As I said before, omitting the first and/or the last value, will assume 0 and the total length, respectively.

But what about step? What’s that?

Until now, we have been using a step of 1 (the default value) by omitting it. The step is how we advance through the list. Think about ‘step’ as jumping values.

my_list = [6, 23, 7, 23, 78, 12, 44]

# We want to get every even element on this list
my_list[0:7:2] # Returns [6, 7, 78, 44]
my_list[::2] # Also returns [6, 7, 78, 44]

# We only want the lower case elements 
other_list = ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd']
other_list[1::2] # Returns ['a', 'b', 'c', 'd']

I don’t know of you thought about it, but… what about negative index? Can we use them?

Well, of course! If 0 is the starting point of a list and 7 its last position, -1 is….the last position. If ‘1’ is one position forward in the list, ‘-1’ is a position backwards. It is logic, right? Think about it as walking. 3 means 3 steps forward, -2 is 2 steps backwards.

alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f']

alphabet_list[0] # Returns 'a'
alphabet_list[5] # Returns 'f'
alphabet_list[-1] # Returns 'f'

While it takes a bit of practice to get the hang of it, as you see it is pretty easy to understand how Python slicing works.

More slicing

We have been slicing list. It is that all we can slice?

Of course not, we can slice any sequential type, such as strings or tuples (immutable lists).

weekly_temperature = (32, 30, 31, 29, 36, 34, 32)

weekly_temperature[:5] # Returns (32, 30, 31, 29, 36)
weekly_temperature[-2:] # Returns (34, 32)

greeting = "Hello, welcome to Let's learn about, my website!"

greeting[0:14] # Returns 'Hello, welcome'
greeting[::2] # Returns 'Hlo ecm oLtslanaot ywbie'

Cool, right? We can return anything we want!

And replace lists and strings (remember, tuple are immutable lists. We can’t change them)

counting = [1, 2, 3, 4, 5, 6]
counting[5:] = ['more numbers']

print(counting) # Prints '[1, 2, 3, 4, 5, 'more numbers']'

I just discover this recently. We just tell “The values ranged from the index of 3 (the fourth value) until the end are replaced by the list to the right of the equal sign”.

This way we can replace in one line what in other languages would mean the creation of a function. Isn’t neat?

Challenge time

guy thinking with a computer

You would be a lousy swimmer if you only learnt how to swim by reading books. Same with developers. Let’s train by doing some old fashioned hard work.

Challenge 1: Return the first 2 elements

We have a list, return the first 2 elements from it.

my_list = [2, 'hello', 'green', 18, 0.5]

Challenge 2: Return the last 3 elements

With the same list, return the last 3 elements from it.

Challenge 3: Return the list without the last element

Pop out now the last element of the list by returning everything but the last one.

Challenge 4: Simplify a long list

Our grocery list is too big! Replace anything from the 4th element to simply ‘cheese’.

grocery_list = ['water', 'bread', 'apples', 'gouda cheese', 'mozzarella', 'edam', 'roquefort', 'brie', 'cheddar']

Challenge 5: Fix the string

Oops, during my weekend I sent a creepy message to my boss my mistake (I swear!). Remove the last 2 extra dots so I can avoid that Monday morning talk.

our_text = "Yes, I'm fine, thanks..."

Take all the time you need to solve the challenges. You can check your solution with mine here.

Next lesson: 11 – Tuples

Follow me on Twitter: https://twitter.com/DavidMM1707

My GitHub: https://github.com/david1707