So you've got an list, tuple or array and you want to get specific sets of sub-elements from it, without any long, drawn out for
loops?
Python has an amazing feature just for that called slicing. Slicing can not only be used for lists, tuples or arrays, but custom data structures as well, with the slice object, which will be used later on in this article.
Understanding the Python Slicing Syntax
To understand how the slice function works in Python, it’s necessary for you to understand what an index is.
You can use the slice function with several different data types in Python – including lists, tuples, and strings. This is because Python uses the concept of indices in all of them.
The “index” of a character or element in a list-like data type is the position of the character or element in the data type. Regardless of what data the data type is holding, index values always begin at zero and end at one less than the number of items in the list.
Python also uses the concept of negative indexes to make data easier to access. Using negative indexes, Python users can access the data in a data type from the end of the container rather than the beginning.
The syntax of slice is:
[python] slice(start, end, step) [/python]
The slice function accepts up to three parameters at the same time. The start parameter is optional and indicates the index of the container which you want to begin slicing the data type from. The value of start defaults to None if no value is provided.
On the other hand, entering the stop parameter is mandatory since it indicates to Python the index to which slicing is supposed to take place. By default, Python will stop the slicing at the value “stop - 1.”
In other words, if the stop value is 5 when using the slice function, Python will only return values till the index value is 4.
The last parameter that Python accepts is called step, and it can be entered optionally as required. It is an integer value that indicates to Python how much the user wants to increment between indexes when slicing the list. The default increment is 1, but users can put any applicable positive integer in step.
Slicing Python Lists/Arrays and Tuples Syntax
Let's start with a normal, everyday list.
[python] >>> a = [1, 2, 3, 4, 5, 6, 7, 8] [/python]
Nothing crazy, just a normal list with the numbers 1 through 8. Now let's say that we really want the sub-elements 2, 3, and 4 returned in a new list. How do we do that?
NOT with a for
loop, that's how. Here's the Pythonic way of doing things:
[python] >>> a[1:4] [2, 3, 4] [/python]
This returns exactly what we want. What the heck does that syntax mean? Good question.
Let me explain it. The 1
means to start at second element in the list (note that the slicing index starts at 0
). The 4
means to end at the fifth element in the list, but not include it. The colon in the middle is how Python's lists recognize that we want to use slicing to get objects in the list.
Advanced Python Slicing (Lists, Tuples and Arrays) Increments
There is also an optional second clause that we can add that allows us to set how the list's index will increment between the indexes that we've set.
In the example above, say that we did not want that ugly 3
returned and we only want nice, even numbers in our list. Easy peasy.
[python] >>> a[1:4:2] [2, 4] [/python]
See, it's as simple as that. That last colon tells Python that we'd like to choose our slicing increment. By default, Python sets this increment to 1
, but that extra colon at the end of the numbers allows us to specify what we want it to be.
Python Slicing (Lists, Tuples and Arrays) in Reverse
Alright, how about if we wanted our list to be backwards, just for the fun of it? Let's try something crazy.
[python] >>> a[::-1] [8, 7, 6, 5, 4, 3, 2, 1] [/python]
What?! What the heck is that?
Lists have a default bit of functionality when slicing. If there is no value before the first colon, it means to start at the beginning index of the list. If there isn't a value after the first colon, it means to go all the way to the end of the list. This saves us time so that we don't have to manually specify len(a)
as the ending index.
Okay. And that -1
I snuck in at the end? It means to increment the index every time by -1
, meaning it will traverse the list by going backwards. If you wanted the even indexes going backwards, you could skip every second element and set the iteration to -2
. Simple.
Slicing Python Tuples
Everything above also works for tuples. The exact same syntax and the exact same way of doing things. I'll give an example just to illustrate that it's indeed the same.
[python] >>> t = (2, 5, 7, 9, 10, 11, 12) >>> t[2:4] (7, 9) [/python]
And that's it. Simple, elegant, and powerful.
Using Python Slice Objects
There is another form of syntax you can use that may be easier to understand. There are objects in Python called slice
objects and the can be used in place of the colon syntax above.
Here's an example:
[python] >>> a = [1, 2, 3, 4, 5] >>> sliceObj = slice(1, 3) >>> a[sliceObj] [2, 3] [/python]
The slice
object initialization takes in 3 arguments with the last one being the optional index increment. The general method format is: slice(start, stop, increment)
, and it is analogous to start:stop:increment
when applied to a list or tuple.
That's it!
Python Slice Examples
To help you understand how to use slice, here are some examples:
#1 Basic Slice Example
Let’s assume you have a list of strings like so:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] [/python]
The following code uses the slice function to derive a sub-list from the items list:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] sub_items = items[1:4] print(sub_items) [/python]
The output of the code is:
[python] ['bike', 'house', 'bank'] [/python]
Since the start index is 1, Python begins the slice with ‘bike.’ On the other hand, the end index is 4, so the slice stops the list at ‘bank.’
For this reason, the end result of the code is a list with the three items: bike, house, and bank. Since this piece of code does not use step, the slice function takes all the values within the range and does not skip any elements.
#2 Slicing the First “N” Elements from a List with Python Slice
Getting the first “N” elements from a list with slice is as simple as using the following syntax:
[python] list[:n] [/python]
Let’s take the same list as the example before, and output the first three elements of the list by slicing:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] sub_items = items[:3] print(sub_items) [/python]
The code will output the following result:
[python] ['car', 'bike', 'house'] [/python]
Note how items[:3] is the same as items[0:3]
#3 Getting the Last “N” Elements from a List with Python Slice
This is similar to the last example, except that we can ask for the last three elements instead of asking for the first three elements.
Here’s how we would do it with the list in the last example:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] sub_items = items[-3:] print(sub_items) [/python]
This code would give us the following results:
[python] ['purse', 'photo', 'box'] [/python]
#4 Slicing Every “Nth” Element from a List Using Python
To do this, we must use the step parameter and return the sublist that we want. Using the same list as before and assuming that we want our code to return every second element:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] sub_items = items[::2] print(sub_items) [/python]
This code would present the following result:
[python] ['car', 'house', 'purse', 'box'] [/python]
#5 Using Python Slice to Reverse a List
The slice function makes reversing a list exceptionally straightforward. All you need to do is give the slice function a negative step, and the function will list the elements from the end of the list to the beginning – reversing it.
Continuing with the example list we were using before:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] reversed_items = items[::-1] print(reversed_items) [/python]
And this will give us the output:
[python] ['box', 'photo', 'purse', 'bank', 'house', 'bike', 'car'] [/python]
#6 Using Python Slice to Substitute Part of a List
Besides making it possible for you to extract parts of a list, the slice function also makes it easy for you to change the elements in a list.
In the following code, we change the first two elements of the list to two new values:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] items[0:2] = ['new car', 'new bike'] print(items) [/python]
The output of the code is:
[python] ['new car', 'new bike', 'house', 'bank', 'purse', 'photo', 'box'] [/python]
#7 Partially Replacing and Resizing a List with Slice
Changing elements and adding new elements to a list is quite easy with the slice function:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] print("The list has {len{items)} elements") items[0:2] = ['new car', 'new bike', 'new watch'] print(items) print ("The list now has {len(items)} elements") [/python]
The code gives the following output:
[python] The list has 7 elements ['new car', 'new bike', 'new watch', 'house', 'bank', 'purse', 'photo', 'box'] The list has 8 elements [/python]
#8 Deleting Elements from Lists Using Slice
Using the example list we’ve been using, here’s how you can delete elements from lists with the slice function:
[python] items = ['car', 'bike', 'house', 'bank', 'purse', 'photo', 'box'] del items[2:4] print(items) [/python]
The output of the code is:
[python] ['car', 'bike', 'purse', 'photo', 'box'] [/python]
If you want to know how to slice strings, that's covered in another article titled How to Get a Sub-string From a String in Python – Slicing Strings.
That's all for now. Hope you enjoyed learning about slicing and I hope it will assist you in your quest.
Peace out.