I compared the answers with python 2.5.2: Show
Note that in Python 3, the 1st was changed to be the same as the 4th. Another option would be to start out with a
The " This article is part of in the series Published: Saturday 30th March 2013 Last Updated: Monday 18th July 2022 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 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 SyntaxTo 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 SyntaxLet'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 [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 Advanced Python Slicing (Lists, Tuples and Arrays) IncrementsThere 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 [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 Python Slicing (Lists, Tuples and Arrays) in ReverseAlright, 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 Okay. And that Slicing Python TuplesEverything 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 ObjectsThere is
another form of syntax you can use that may be easier to understand. There are objects in Python called Here's an example: [python] >>> a = [1, 2, 3, 4, 5] >>> sliceObj = slice(1, 3) >>> a[sliceObj] [2, 3] [/python] The That's it! Python Slice ExamplesTo help you understand how to use slice, here are some examples: #1 Basic Slice ExampleLet’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 SliceGetting 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. About The Author
I'm a python enthusiast that loves programming as a hobby. Entrepreneur in training, I'm working on cultivating sources of passive income in order to pursue the things I love to do.
How do I select a specific item in a list?Click the first item, then press the SHIFT key and hold it. Click the last item and release the SHIFT key. To select adjacent items, you can also use the mouse. Click the left mouse button on the first item, hold the mouse button, move the cursor to the last item and then release the mouse button.
How do I extract a specific item from a list in Python?Use the syntax [list[index] for index in index_list] to get a list containing the elements in list at the indices in index_list .. a_list = ["apple", "pear", "banana", "peach"]. indices = [1, 3]. extracted_elements = [a_list[index] for index in indices]. Can you slice a list in Python?In short, slicing is a flexible tool to build new lists out of an existing list. Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges.
What is used to extract a part of the list?As well as using slicing to extract part of a list (i.e. a slice on the right hand sign of an equal sign), you can set the value of elements in a list by using a slice on the left hand side of an equal sign.
|