{"id":10696,"date":"2018-10-03T19:27:24","date_gmt":"2018-10-03T16:27:24","guid":{"rendered":"https:\/\/railsware.com\/blog\/?p=10696"},"modified":"2025-01-22T15:29:44","modified_gmt":"2025-01-22T12:29:44","slug":"indexing-and-slicing-for-lists-tuples-strings-sequential-types","status":"publish","type":"post","link":"https:\/\/railsware.com\/blog\/indexing-and-slicing-for-lists-tuples-strings-sequential-types\/","title":{"rendered":"Indexing and Slicing for Lists, Tuples, Strings, other Sequential Types in Python"},"content":{"rendered":"\n<p class=\"intro-text\">List is arguably the most useful and ubiquitous type in Python. One of the reasons it&#8217;s so handy is Python slice notation. In short, slicing is a flexible tool to build new lists out of an existing list.<\/p>\n\n\n\n<p>Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges. Also, any new data structure can add its support as well. This is greatly used (and abused) in NumPy and Pandas libraries, which are so popular in Machine Learning and Data Science. It\u2019s a good example of &#8220;learn once, use everywhere&#8221;.<\/p>\n\n\n\n<p>In this article, we will focus on indexing and slicing operations over Python&#8217;s lists. Most of the examples we will discuss can be used for any sequential data type. Only mutable assignment and deletion operations are not applicable to immutable sequence types like tuples, strings, bytes, and ranges.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"2400\" height=\"1260\" src=\"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/Python-for-Data-Science-illustration.jpg\" alt=\"Using Python in Machine Learning\" class=\"wp-image-10715\" srcset=\"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/Python-for-Data-Science-illustration.jpg 2400w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/Python-for-Data-Science-illustration-360x189.jpg 360w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/Python-for-Data-Science-illustration-768x403.jpg 768w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/Python-for-Data-Science-illustration-1024x538.jpg 1024w\" sizes=\"auto, (max-width: 2400px) 100vw, 2400px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Indexing<\/h2>\n\n\n\n<p>Before discussing slice notation, we need to have a good grasp of indexing for sequential types.<\/p>\n\n\n\n<p>In Python, list is akin to arrays in other scripting languages(Ruby, JavaScript, PHP). It allows you to store an enumerated set of items in one place and access an item by its position &#8211; index.<\/p>\n\n\n\n<p>Let&#8217;s take a simple example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> colors = ['red', 'green', 'blue', 'yellow', 'white', 'black']\n<\/pre>\n\n\n\n<p>Here we defined a list of colors. Each item in the list has a value(color name) and an index(its position in the list). Python uses <strong>zero-based<\/strong> indexing. That means, the first element(value &#8216;red&#8217;) has an index 0, the second(value &#8216;green&#8217;) has index 1, and so on.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"1644\" height=\"454\" src=\"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/positive-indexes.png\" alt=\"\" class=\"wp-image-10699\" srcset=\"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/positive-indexes.png 1644w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/positive-indexes-360x99.png 360w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/positive-indexes-768x212.png 768w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/positive-indexes-1024x283.png 1024w\" sizes=\"auto, (max-width: 1644px) 100vw, 1644px\" \/><\/figure>\n\n\n\n<p>To access an element by its index we need to use square brackets:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> colors = ['red', 'green', 'blue', 'yellow', 'white', 'black']\n>>> colors[0]\n'red'\n>>> colors[1]\n'green'\n>>> colors[5]\n'black'\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Negative indexes<\/h3>\n\n\n\n<p>Using indexing we can easily get any element by its position. This is handy if we use position from the head of a list. But what if we want to take the last element of a list? Or the penultimate element? In this case, we want to enumerate elements from the tail of a list.<\/p>\n\n\n\n<p>To address this requirement there is negative indexing. So, instead of using indexes from zero and above, we can use indexes from -1 and below.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"1644\" height=\"468\" src=\"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/negative-indexes.png\" alt=\"\" class=\"wp-image-10698\" srcset=\"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/negative-indexes.png 1644w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/negative-indexes-360x102.png 360w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/negative-indexes-768x219.png 768w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/negative-indexes-1024x292.png 1024w\" sizes=\"auto, (max-width: 1644px) 100vw, 1644px\" \/><\/figure>\n\n\n\n<p>In negative indexing system -1 corresponds to the last element of the list(value &#8216;black&#8217;), -2 to the penultimate (value &#8216;white&#8217;), and so on.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> colors = ['red', 'green', 'blue', 'yellow', 'white', 'black']\n>>> colors[-1]\n'black'\n>>> colors[-2]\n'white'\n>>> colors[-6]\n'red'\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Assignment<\/h3>\n\n\n\n<p>Before we used indexing only for accessing the content of a list cell. But it&#8217;s also possible to change cell content using an assignment operation:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> basket = ['bread', 'butter', 'milk']\n>>> basket[0] = 'cake'\n>>> basket\n['cake', 'butter', 'milk']\n>>> basket[-1] = 'water'\n>>> basket\n['cake', 'butter', 'water']\n<\/pre>\n\n\n\n<p>We can freely use positive or negative indexing for assignment.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Deletion<\/h3>\n\n\n\n<p>We can also easily delete any element from the list by using indexing and <code>del<\/code> statement:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> basket = ['bread', 'butter', 'milk']\n>>> del basket[0]\n>>> basket\n['butter', 'milk']\n>>> del basket[1]\n>>> basket\n['butter']\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Indexing for other Sequential Types<\/h3>\n\n\n\n<p>Read-only indexing operations work perfectly well for all sequential types. But assignment and deletion operations are not applicable to immutable sequential types.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Slice Notation<\/h2>\n\n\n\n<p>As it was shown, indexing allows you to access\/change\/delete only a single cell of a list. What if we want to get a sublist of the list. Or we want to update a bunch of cells at once? Or we want to go on a frenzy and extend a list with an arbitrary number of new cells in any position?<\/p>\n\n\n\n<p>Those and lots of other cool tricks can be done with slice notation. Let&#8217;s look at this subject &#8211; feel free to follow along on your own editor or with an online <a href=\"https:\/\/www.scaler.com\/topics\/python\/online-python-compiler\/\" title=\"Python compiler\">Python compiler<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Usage of Slices<\/h3>\n\n\n\n<p>Let&#8217;s create a basic list:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n<\/pre>\n\n\n\n<p>What if we want to take a sublist from the <code>nums<\/code> list? This is a snap when using slice:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> some_nums = nums[2:7]\n>>> some_nums\n[30, 40, 50, 60, 70]\n<\/pre>\n\n\n\n<p>So, here is our first example of a slice: <em>2:7<\/em>. The full slice syntax is: <em>start:stop:step<\/em>. <code>start<\/code> refers to the index of the element which is used as a start of our slice. <code>stop<\/code> refers to the index of the element we should stop just before to finish our slice. <code>step<\/code> allows you to take each nth-element within a <em>start:stop<\/em> range.<\/p>\n\n\n\n<p>In our example <code>start<\/code> equals <code>2<\/code>, so our slice starts from value <code>30<\/code>. <code>stop<\/code> is <code>7<\/code>, so the last element of the slice is <code>70<\/code> with index <code>6<\/code>. In the end, slice creates a new list(we named it <code>some_nums<\/code>) with selected elements.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"1534\" height=\"764\" src=\"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/first-slice.png\" alt=\"\" class=\"wp-image-10697\" srcset=\"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/first-slice.png 1534w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/first-slice-360x179.png 360w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/first-slice-768x382.png 768w, https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/first-slice-1024x510.png 1024w\" sizes=\"auto, (max-width: 1534px) 100vw, 1534px\" \/><\/figure>\n\n\n\n<p>We did not use <code>step<\/code> in our slice, so we didn\u2019t skip any element and obtained all values within the range.<\/p>\n\n\n\n<p>With slices we can extract an arbitrary part of a list, e.g.:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[0:4]\n[10, 20, 30, 40]\n<\/pre>\n\n\n\n<p>Here we start from the first element(index <code>0<\/code>) and take a list till the element with index <code>4<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Taking n first elements of a list<\/h3>\n\n\n\n<p>Slice notation allows you to skip any element of the full syntax. If we skip the <code>start<\/code> number then it starts from <code>0<\/code> index:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[:5]\n[10, 20, 30, 40, 50]\n<\/pre>\n\n\n\n<p>So, <em>nums[:5]<\/em> is equivalent to <em>nums[0:5]<\/em>. This combination is a handy shortcut to take n first elements of a list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Taking n last elements of a list<\/h3>\n\n\n\n<p>Negative indexes allow us to easily take n-last elements of a list:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[-3:]\n[70, 80, 90]\n<\/pre>\n\n\n\n<p>Here, the <code>stop<\/code> parameter is skipped. That means you take from the <code>start<\/code> position, till the end of the list. We start from the third element from the end (value <code>70<\/code> with index <code>-3<\/code>) and take everything to the end.<\/p>\n\n\n\n<p>We can freely mix negative and positive indexes in <code>start<\/code> and <code>stop<\/code> positions:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[1:-1]\n[20, 30, 40, 50, 60, 70, 80]\n>>> nums[-3:8]\n[70, 80]\n>>> nums[-5:-1]\n[50, 60, 70, 80]\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Taking all but n last elements of a list<\/h3>\n\n\n\n<p>Another good usage of negative indexes:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[:-2]\n[10, 20, 30, 40, 50, 60, 70]\n<\/pre>\n\n\n\n<p>We take all but the last two elements of original list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Taking every nth-element of a list<\/h3>\n\n\n\n<p>What if we want to have only every 2-nd element of <code>nums<\/code>? This is where the <code>step<\/code> parameter comes into play:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[::2]\n[10, 30, 50, 70, 90]\n<\/pre>\n\n\n\n<p>Here we omit <code>start<\/code>\/<code>stop<\/code> parameters and use only <code>step<\/code>. By providing <code>start<\/code> we can skip some elements:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums[1::2]\n[20, 40, 60, 80]\n<\/pre>\n\n\n\n<p>And if we don&#8217;t want to include some elements at the end, we can also add the <code>stop<\/code> parameter:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums[1:-3:2]\n[20, 40, 60]\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Using Negative Step and Reversed List<\/h3>\n\n\n\n<p>We can use a negative <code>step<\/code> to obtain a reversed list:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[::-1]\n[90, 80, 70, 60, 50, 40, 30, 20, 10]\n<\/pre>\n\n\n\n<p>Negative <code>step<\/code> changes a way, slice notation works. It makes the slice be built from the tail of the list. So, it goes from the last element to the first element. That&#8217;s why we get a reversed list with a negative step.<\/p>\n\n\n\n<p>Due to this peculiarity, <code>start<\/code> and <code>stop<\/code> should be provided from right to left as well. E.g., if you want to have a reversed list which starts from <code>80<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[-2::-1]\n[80, 70, 60, 50, 40, 30, 20, 10]\n<\/pre>\n\n\n\n<p>So, we start from the <code>-2<\/code> element (value <code>80<\/code>) and go from right to left collecting all the elements in a reversed list.<\/p>\n\n\n\n<p>We can use <code>stop<\/code> value to stop taking before some element. E.g., let&#8217;s not include <code>20<\/code> and <code>10<\/code> values:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[-2:1:-1]\n[80, 70, 60, 50, 40, 30]\n<\/pre>\n\n\n\n<p>We use <code>1<\/code> for <code>stop<\/code> index, which is the element with value <code>20<\/code>. So, we go from 80 till 30, not including value <code>20<\/code>.<\/p>\n\n\n\n<p>It&#8217;s a bit baffling that with a negative <code>step<\/code>, <code>stop<\/code> index is located before <code>start<\/code>. Negative <code>step<\/code> turns everything upside down.<\/p>\n\n\n\n<p>Of course, we can use an arbitrary negative <code>step<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[-2:1:-3]\n[80, 50]\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Slice and Copying<\/h3>\n\n\n\n<p>One important thing to notice &#8211; is that list slice creates a shallow copy of the initial list. That means, we can safely modify the new list and it will not affect the initial list:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> first_five = nums[0:5]\n>>> first_five[2] = 3\n>>> first_five\n[10, 20, 3, 40, 50]\n>>> nums\n[10, 20, 30, 40, 50, 60, 70, 80, 90]\n<\/pre>\n\n\n\n<p>Despite our mutating the element under index <code>2<\/code>, it does not affect the <code>nums<\/code> list, because <code>first_five<\/code> list &#8211; is a partial copy of <code>nums<\/code> list.<\/p>\n\n\n\n<p>There is the shortest form of slice notation &#8211; just colons <em>nums[:]<\/em>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums_copy = nums[:]\n>>> nums_copy[0] = 33\n>>> nums_copy\n[33, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums\n[10, 20, 30, 40, 50, 60, 70, 80, 90]\n<\/pre>\n\n\n\n<p>It creates a shallow copy of the whole list and is a good shorthand when you need a copy of the original list.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Slice Object<\/h3>\n\n\n\n<p>But what if we want to use the same slice over and over again. Is there a way to create a slice object instead of using just the syntactic form?<\/p>\n\n\n\n<p>This can be done using <code>slice<\/code> function:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> five_items_after_second = slice(2, 2 + 5)\n>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> colors = ['red', 'green', 'blue', 'yellow', 'white', 'black', 'silver']\n>>> nums[five_items_after_second]\n[30, 40, 50, 60, 70]\n>>> colors[five_items_after_second]\n['blue', 'yellow', 'white', 'black', 'silver']\n<\/pre>\n\n\n\n<p><code>slice<\/code> function accepts arguments in the same order as in slice notation, and if you need to skip some element, just use <code>None<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> all_but_two_last = slice(None, -2)\n>>> nums[all_but_two_last]\n[10, 20, 30, 40, 50, 60, 70]\n>>> reversed = slice(None, None, -1)\n>>> nums[reversed]\n[90, 80, 70, 60, 50, 40, 30, 20, 10]\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Slice Assignment<\/h3>\n\n\n\n<p>Python supports slice assignment operation, which allows us to make a bunch of neat operations over an existing list. Unlike previous slice operations, these mutate the original object in place. That&#8217;s why they are not applicable to immutable sequential types.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Substitute part of a list<\/h4>\n\n\n\n<p>Slice assignment allows you to update a part of a list with new values:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[:4] = [1,2,3,4]\n>>> nums\n[1, 2, 3, 4, 50, 60, 70, 80, 90]\n<\/pre>\n\n\n\n<p>Here we do not change the number of elements in the list. Only some list values are updated.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Replace and Resize part of the list<\/h4>\n\n\n\n<p>We can replace part of a list with a bigger chunk instead:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[:4] = [1,2,3,4,5,6,7]\n>>> nums\n[1, 2, 3, 4, 5, 6, 7, 50, 60, 70, 80, 90]\n<\/pre>\n\n\n\n<p>In this case we extend the original list.<\/p>\n\n\n\n<p>It&#8217;s also possible to replace a bigger chunk with a smaller number of items:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[:4] = [1]\n>>> nums\n[1, 50, 60, 70, 80, 90]\n<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Replace Every n-th Element<\/h4>\n\n\n\n<p>Adding <code>step<\/code> allows to replace each n-th element with a new value:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[::2] = [1,1,1,1,1]\n>>> nums\n[1, 20, 1, 40, 1, 60, 1, 80, 1]\n<\/pre>\n\n\n\n<p>Using slice assignment with <code>step<\/code> sets a limitation on the list we provide for assignment. The provided list should exactly match the number of elements to replace. If the length does not match, Python throws the exception:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[::2] = [1,1,1]\nTraceback (most recent call last):\n  File \"\", line 1, in \nValueError: attempt to assign sequence of size 3 to extended slice of size 5\n<\/pre>\n\n\n\n<p>We can also use negative <code>step<\/code>:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[::-2] = [1,2,3,4,5]\n>>> nums\n[5, 20, 4, 40, 3, 60, 2, 80, 1]\n<\/pre>\n\n\n\n<p>By providing <code>start<\/code> and <code>stop<\/code> values we can narrow the replacement area:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> nums[1:5:2] = [2, 4]\n>>> nums\n[10, 2, 30, 4, 50, 60, 70, 80, 90]\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Slice Deletion<\/h3>\n\n\n\n<p>We can also use <code>del<\/code> statement to remove a slice out of a list:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> del nums[3:7]\n>>> nums\n[10, 20, 30, 80, 90]\n<\/pre>\n\n\n\n<p>Here we\u2019ve removed a bunch of elements in the middle of <code>nums<\/code> list.<\/p>\n\n\n\n<p>We can also provide <code>step<\/code> parameter to slice and remove each n-th element:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> del nums[::2]\n>>> nums\n[20, 40, 60, 80]\n<\/pre>\n\n\n\n<p>With the full syntax, we can set boundaries for the elements to be removed:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n>>> del nums[1:7:2]\n>>> nums\n[10, 30, 50, 70, 80, 90]\n<\/pre>\n\n\n\n<p>So, we start deletion from 20(index 1) and remove each 2-nd element till the value 80(index 7).<\/p>\n\n\n\n<p>And because slice deletion mutates the underlying object, it\u2019s not applicable to immutable sequential types.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<p>We discussed two key list operations: indexing and slicing. Both concepts are crucial to efficient Python use.<\/p>\n\n\n\n<p>This article prepared background for tackling indexing and slicing in <code>NumPy<\/code> <code>ndarrays<\/code> and <code>Pandas<\/code> <code>Series<\/code> and <code>DataFrame<\/code> objects. There are a lot of similarities between these structures, but there are also a lot of subtle differences and gotchas which will be discussed in upcoming articles dedicated to the machine learning techniques the Railsware team makes use of.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Read more<\/h2>\n\n\n\n<div class=\"sources\">\n  \n  <ul class=\"sources-list\">\n    \n          <li class=\"sources-list__item\">\n            <a href=\"https:\/\/railsware.com\/blog\/best-libraries-and-tools-to-start-off-with-machine-learning-and-ai\/\" target=\"_blank\">\n              <span class=\"sources-list__long-text\">\n                Best Libraries and Tools to Start off with Machine Learning and AI              <\/span>\n            <i class=\"icon-arrow-right\"><\/i>\n          <\/a>\n          <\/li>\n        \n      \n          <li class=\"sources-list__item\">\n            <a href=\"https:\/\/railsware.com\/services\/ai-machine-learning-consulting\/\" target=\"_self\">\n              <span class=\"sources-list__long-text\">\n                Artificial Intelligence &amp; Machine Learning Consulting Services              <\/span>\n            <i class=\"icon-arrow-right\"><\/i>\n          <\/a>\n          <\/li>\n        \n            <\/ul>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Python, one of the most in-demand machine learning languages, supports slice notation for any sequential data type like lists, strings, and others. Discover more about indexing and slicing operations over Python\u2019s lists and any sequential data type.<\/p>\n","protected":false},"author":25,"featured_media":10713,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[3],"tags":[],"coauthors":["Sergii Boiko"],"class_list":["post-10696","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development"],"acf":[],"aioseo_notices":[],"categories_data":[{"name":"Engineering","link":"https:\/\/railsware.com\/blog?category=development"}],"post_thumbnails":"https:\/\/railsware.com\/blog\/wp-content\/uploads\/2018\/10\/Python-for-Data-Science-illustration.jpg","amp_enabled":true,"_links":{"self":[{"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/posts\/10696","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/users\/25"}],"replies":[{"embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/comments?post=10696"}],"version-history":[{"count":23,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/posts\/10696\/revisions"}],"predecessor-version":[{"id":18003,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/posts\/10696\/revisions\/18003"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/media\/10713"}],"wp:attachment":[{"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/media?parent=10696"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/categories?post=10696"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/tags?post=10696"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/railsware.com\/blog\/wp-json\/wp\/v2\/coauthors?post=10696"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}