Python Slicing – How to Slice an Array and What Does [::-1] Mean?

Dillion Megida

Slicing an array is the concept of cutting out – or slicing out – a part of the array. How do you do this in Python? I'll show you how in this article.

If you like watching video content to supplement your reading, here's a video version of this article as well.

What is an Array?

An array is a data structure that allows you to store multiple items of the same data type in order in a variable at the same time. You can access each of these items by their index (location in the order).

They are a bit similar to lists in Python, it's just that lists allow you to store multiple items of different data types . Also, while lists are built-in, arrays aren't.

How to Access Values in an Array in Python

Here's the syntax to create an array in Python:

As the array data type is not built into Python by default, you have to import it from the array module. We import this module as arr .

Using the array method of arr , we can create an array by specifying a typecode (data type of the values) and the values stored in the array.

Here's a table showing the acceptable typecodes:

Typecodes gotten from the Python documentation .

Here's an example array in Python:

We created an array of integer values from 1 to 5 here. We also accessed the second value by using square brackets and its index in the order, which is 1 .

How to Slice an Array in Python

Let's say you want to slice a portion of this array and assign the slice to another variable. You can do it using colons and square brackets. The syntax looks like this:

The start index specifies the index that the slicing starts from. The default is 0 .

The end index specifies the index where the slicing ends (but excluding the value at this index). The default is the length of the array.

The step argument specifies the step of the slicing. The default is 1 .

Let's see some examples that cover different ways in which arrays can be sliced.

How to slice without a start or end index

When you slice without a start or end index, you basically get a whole copy of the array:

As you can see here, we have a copy of the numbers array.

It's also worth noting that the slicing action does not affect the original array. With slicing, you only "copy a portion" of the original array.

How to slice with a start index

For example, if you want to slice an array from a specific start value to the end of the array, here's how:

By passing 2: in the square brackets, the slicing starts from index 2 (which holds value 3) up until the end of the array, as you can see in the results.

How to slice with an end index

For example, if you want to slice an array from the first value to the third, here's how:

By passing :3 in the square brackets, slicing starts from the 0 index (by default, since not specified) up until the third index we specified.

As mentioned earlier, the slicing excludes the value at the third index. So in the results, as you find in the copy variable, the values returned are from index 0 through index 2 .

How to slice with a start and end index

What if you want to specify the starting and ending points of the slicing? Here's how:

By using a number, then a colon, followed by a number in square brackets, you can specify a starting and ending indexes, respectively.

In our case, we used 1 and 4 as in [1:4] . From the results, you see that the slicing starts from the value at index 1 which is 2 , up until the value before the index 4 , which is 4 (at index 3).

How to slice with steps

When you specify a start and end index of 1 and 5, respectively, slicing will select values at index 1 , index 2 (1 increment to the previous index), index 3 (1 increment to the previous index) and index 4 (and one increment to the previous index).

In this slicing, a step of 1 is used by default. But you can provide a different step. Here's how:

By adding another colon, you can specify a step. So we have [start:stop:step] .

In our example, the start is 1 , the end is 4 and the step is 2. Slicing starts from the value at index 1 which is 2 , then the next value will be at the previous index plus the step, which is 1 + 2 equals 3. The value at index 3 is 4 so that is added to the slice. The next index will be 5 ( 3 + 2 ) but since 5 exceeds the stop index, it will not be added to the slice.

As you can see in the code, the sliced copy is just 2 and 4.

How to slice with negative start and end indexes

The start or stop indexes can also be negative. Negative indexes count from the end of the array. This means a negative index is the last value in an array:

By using a negative 1 here, you see that 5 is returned, which is from the end of an array.

With a slice expression like [-3:-1] , this means a start index of -3 and end index of -1 . Let's see how that works with our array:

The slice starts from index -3 (which is the third value from the end of the array, that is 3) and stops at index -1 (which is the last value in the array, that is 5). Slicing doesn't include the last value so we have 3 and 4.

Combining a negative start index and a positive end index (or vice versa) will not work as you'll be going different directions at once.

How to slice with negative steps

You can use negative steps, which means the steps decrement for the slicing. Here's an example:

Here, we specify a start of index 2 , no end, and a step of -1 . Slicing here will start from index 2 which is 3. The negative steps mean the next value in the slice will be at an index smaller than the previous index by 1. This means 2 - 1 which is 1 so the value at this index, which is 2 will be added to the slice.

This goes on reversed until it gets to the end of the array which is index 0 . The sliced array results in values of 3, 2, and 1.

What does [::-1] mean?

Have you seen this expression anywhere in Python before? Well, here's what it means: there's no start index specified, nor an end index, only a negative step of -1 .

The start index defaults to 0 , so by using -1 step, the slicing will contain values at the following indexes: -1 ( 0 - 1 ), -2 ( -1 - 1 ), -3 ( -2 - 1 ), -4 ( -3 - 1 ) and -5 ( -4 - 1 ). Pretty much a reversed copy of the array.

Here's the code for it:

As you can see, this is a simple way to reverse an array.

Wrapping Up

In this article, we've briefly looked at how to declare arrays in Python, how to access values in an array, and also how to cut – or slice – a part of an array using a colon and square brackets.

We also learned how slicing works with steps and positive/negative start and stop indexes.

You can learn more about arrays here: Python Array Tutorial – Define, Index, Methods .

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Home » Advanced Python » Python Slicing in Depth

Python Slicing in Depth

Summary : in this tutorial, you’ll learn about Python slicing and how to use it to extract data from and assign data to a sequence.

Python slicing review

So far you’ve learned about slicing such as list slicing .

Technically, slicing relies on indexing. Therefore, slicing only works with sequence types .

For mutable sequence types such as lists , you can use slicing to extract and assign data. For example:

However, you can use slicing to extract data from immutable sequences. For example:

If you attempt to use slicing to assign data to an immutable sequence, you’ll get an error. For example:

The slicing seq[start:stop] returns the elements starting at the index start up to the index stop - 1 . Therefore, it’s easier to visualize that the indexes are between the elements when you slice the sequence:

Python Slicing

Python slice type

Everything in Python is an object including the slice. A slice is actually an object of the slice type. When you use the slicing notation:

The start:stop is a slice object.

For example:

So instead of using the slicing notation:

… you can use the slice object instead:

Python Slicing: start and stop bounds

The slice seq[start:stop] selects elements starting at the index start and stopping at the index stop (excluding the element at the index stop ).

In other words, it returns all elements of the sequence at the index n where n satisfies the following expression:

When start or stop is greater than the length of the sequence:

… Python uses len(seq) for the start or stop .

Both start and stop are optional. The start defaults to 0 and stop defaults to len(seq) when you don’t specify it.

The following example returns the entire list:

Since the stop bound is 100, Python uses the len(colors) for the stop bound.

The following example returns an empty list:

Because the start is 10, Python assigns the len(colors) to it.

Negative start and stop bounds

The slice object also accepts negative start and stop bounds. The following example uses the negative start and stop bounds to slice a list:

To get the 'blue' and 'orange' elements from the colors list, you can combine the negative and positive bounds:

slice assignment in python

The step value

Slices support the third argument, which is the step value. The step value defaults to 1 if you don’t specify it:

It’s equivalent to:

See the following example:

The indices method

A slice object essentially defines a sequence of indices for selecting elements of a sequence.

To make it more convenient, the slice type has the indices method that returns the equivalent range (start, stop, step) for any slice of a sequence with a specified length:

It returns a new tuple:

And you can use the values of this tuple to generate a list of indices using the range function. For example:

How it works.

  • First, create a slice object whose start is 0, stop is 4, and step is 2.
  • Second, return a tuple of indices of the slice of the sequence whose length is the length of the colors list.
  • Third, pass the result tuple to the range function to select elements from the colors list.
  • Slicing only works for sequence types including mutable and immutable sequences.
  • A slice is an object the slice type.

DEV Community

DEV Community

Isabelle M.

Posted on Oct 16, 2022 • Originally published at 30secondsofcode.org

Understanding Python's slice assignment

Basic syntax.

In order to understand Python's slice assignment, you should at least have a decent grasp of how slicing works. Here's a quick recap:

Where start_at is the index of the first item to be returned (included), stop_before is the index of the element before which to stop (not included) and step is the stride between any two items.

Slice assignment has the same syntax as slicing a list with the only exception that it's used on the left-hand side of an expression instead of the right-hand side. Since slicing returns a list, slice assignment requires a list (or other iterable). And, as the name implies, the right-hand side should be the value to assign to the slice on the left-hand side of the expression. For example:

Changing length

The part of the list returned by the slice on the left-hand side of the expression is the part of the list that's going to be changed by slice assignment. This means that you can use slice assignment to replace part of the list with a different list whose length is also different from the returned slice. For example:

If you take empty slices into account, you can also insert elements into a list without replacing anything in it. For example:

Using steps

Last but not least, step is also applicable in slice assignment and you can use it to replace elements that match the iteration after each stride. The only difference is that if step is not 1 , the inserted list must have the exact same length as that of the returned list slice. For example:

Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

furkangozukara profile image

Compared Effect Of Image Captioning For SDXL Fine-tuning / DreamBooth Training for a Single Person, 10.3 GB VRAM via OneTrainer

Furkan Gözükara - Mar 28

rutamstwt profile image

Vertex AI: Building a Q&A System with Semantic Search

Rutam Bhagat - Apr 1

ashcode98 profile image

Day 5 of #100DaysOFCode

Ashish Prajapati - Mar 28

mekkj98 profile image

Leetcode: Reveal Cards In Increasing Order

keshav jha - Apr 10

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Slicing Lists in Python: A Comprehensive How-To Guide

Slicing is a very useful technique in Python that allows you to extract subsets or slices from sequences like lists, tuples, and strings. Slicing provides an efficient and convenient way to get a specific subset range from a list without having to loop through and index each item individually.

In this comprehensive guide, you will learn what list slicing is, how it works under the hood, and how to leverage slicing operations to extract, modify or analyze subsets of list data in Python.

We will cover the basics of slicing syntax, slice object internals, and practical applications with code examples. You will also learn advanced techniques like multidimensional slicing on nested lists and gotchas to avoid when slicing mutables.

By the end, you will have a deep understanding of slicing in Python and be able to use it proficiently in your own programs for efficient data extraction and processing. The knowledge is useful for Python developers, data scientists, and anyone working with sequential data structures.

Table of Contents

What is list slicing in python, omitting start and end indices, negative indices, stepping or stride value, empty slices, multidimensional slicing, practical examples of list slicing in python, slicing gotchas and best practices.

List slicing in Python is an operation that allows you to retrieve a range of items from a list by specifying start and end indices. It returns a new list containing the extracted elements.

The basic syntax for slicing a list is:

  • original_list is the list you want to slice.
  • start is the index of the first element you want included in the sliced list.
  • end is the index of the first element you want excluded from the sliced list.
  • new_list contains the sliced elements from index start up to but not including end.

For example:

This slices fruits from index 1 (inclusive) to index 3 (exclusive) and assigns the new sliced list to fruits_subset .

Some key properties of slicing lists in Python:

  • Slicing extracts a new list with the specified items. It does not modify the original list.
  • The start index is inclusive and the end index is exclusive.
  • You can omit either start or end index to slice from start/end of list by default.
  • Slicing handles negative indices to refer to positions from end of list.
  • Returns empty list if start >= end indices.
  • Supports stepping with a stride value.

We’ll explore these in more detail with examples next.

How List Slicing Works in Python

Slicing notation in Python is implemented through slice objects. A slice object represents the start, stop, and step values given to slice a sequence, and contains metadata about the slicing operation.

The slice object is created by calling slice() built-in and passed to the sequence indexing operator [] .

Understanding what happens internally helps explain the behavior and flexibility of slicing notation in Python.

When a slice object is passed to the indexing operator, the sequence looks up its _ _getitem_ _ method to handle the slice and extract the subset items accordingly.

Now let’s look at different ways to slice lists using this slice object notation.

If you omit start index, 0 is taken by default:

Similarly, if you omit end, it slices all the way to the end by default:

You can also omit both to make a full slice copy of the entire list:

Python allows negative indices for slicing, which refer to positions counted backwards from the end of the list.

Here, -3 refers to index 2 from start and -1 refers to index 4 from start when counted backwards from the end.

Negative indices provide an easy way to slice items from the end of a list without needing to know the exact length.

You can also specify a step or stride value to skip items while slicing:

The third argument 2 specifies a step of 2. So it extracts every alternate item from index 0 to end.

Stepping works with negative stride too:

Here, step -1 reverses the list by going backwards from end to start.

If start index >= end index, slicing returns an empty list since no items exist in that range:

The slice is essentially invalid in these cases.

Slicing also works on nested lists (lists within lists) to extract subsets from sublists:

You can slice both the outer and inner lists separately.

This multidimensional slicing provides a very flexible way to extract sections from matrix or grid-like data structures in Python.

Now let’s look at some practical examples of how list slicing can be used in real code.

1. Getting a sublist with specific indices

Use simple slicing to extract part of a list:

2. Omitting indices for start/end defaults

Utilize default start and end values:

3. Negative index for slicing from end

Get the last 3 items by negative index:

4. Skipping items with step value

Extract every 3rd item:

5. Reversing list with negative step

Reverse the entire list:

6. Copying a list

Make a full slice copy:

7. Removing list section in-place

Delete section by assigning an empty slice:

8. Multidimensional slice on matrix

Extract subsets from nested lists:

These are some common use cases for slicing lists in Python. The key strengths are efficiently extracting sections, reversing, stepping through items, and working with multidimensional data.

While slicing syntax is very flexible, there are some best practices to keep in mind:

Slicing does not modify the original list - It extracts a new list with a copy of the sliced data. To modify in-place, delete slice or assign to slice.

Avoid slicing mutable objects - Slicing mutable objects like dicts or sets returns a shallow copy that still references the original. Changes to sliced copy affect original.

Handle out of bound errors - Slicing indices outside of the valid range will raise an IndexError . Catch exceptions or check bounds first.

Use negative indices wisely - It can make code harder to understand vs positive indices. Best for slicing relative to end.

Prefer start:end over start:len(list) - Knowing the length to slice from start to end is inefficient. Omit end instead.

Use stepped slices for regular skips - Stepping is useful for skipping fixed intervals instead of manual loops.

Test edge cases on empty lists - Be careful slicing empty lists and watch for off-by-one errors.

Following best practices will help you avoid subtle bugs and write clean, efficient list slicing code.

This guide covered the fundamentals of slicing in Python - from basic syntax, to internals, practical examples, advanced techniques, and common gotchas.

Key takeaways:

  • Slicing extracts subsequences from lists, tuples, strings without modifying originals
  • Slice object passed to __getitem__ represents start, stop, and step
  • Omit indices to slice from defaults of start/end
  • Use negative indices to refer to positions from end
  • Step provides skip intervals for slicing
  • Multidimensional slicing works on nested collections
  • Avoid slicing mutable objects and watch edge cases

You should now be able to leverage slicing for efficient data extraction, processing, and analysis in your Python code. Slicing is a universally useful technique for Python developers.

Some next topics to explore further are NumPy array slicing, Pandas dataframe slicing, and generator expressions for lazy slicing.

I hope you found this guide helpful in deepening your understanding of this core Python language feature. Let me know if you have any other questions!

  •    python
  •    data-structures

List slicing in Python

Trey Hunner smiling in a t-shirt against a yellow wall

Sign in to change your settings

Sign in to your Python Morsels account to save your screencast settings.

Don't have an account yet? Sign up here .

Let's talk about slicing lists in Python.

Getting the first N elements from a list

Let's say we have a fruits variable that points to a list :

We can get an item from this list by indexing it:

If we put a colon and another number inside the square brackets, we'll slice this list instead of indexing it:

Slicing a list gives us back a new list. We're getting a list of the first three items within our original list.

Slicing makes a new list

Note that the original list is unchanged:

Slicing takes a portion of the elements from our original list and makes a new list out of them:

The start index is inclusive but the stop index is exclusive

What do you think we might get if we were to slice our list from 1 to 3 instead of from 0 to 3 ?

Here are some guesses:

  • Two items starting from the second item
  • Three items starting from the second item
  • The same three items as before

What's your guess?

When we slice with 1 and 3 , we only get 2 items this time:

With Python's slicing syntax, the first item is the start index , and the second item is the stop index . The start index is inclusive , but the stop index is exclusive , meaning Python stops just before the stop index.

So we got the items at index 1 and index 2 because we stopped just before index 3 .

Default slice start/stop values

The start and stop values are both optional when slicing.

If we don't supply a start index, we'll start at the beginning of the list (index 0 ):

So that gave us the first 3 items.

If we don't supply a stop index, we'll stop at the end of the list:

So this slice gave us everything from the second item onward.

Why the stop index isn't included in slices

You may be wondering, why is the start index included, but the stop index is excluded?

The exclusivity of the stop index actually has a nice side effect: if you slice up to index 3 and then start slicing again from 3 onward, those two slices won't overlap .

So if we concatenate those slices back together, we'd get back something equivalent to our original list:

Here's an example of making a new list that moves the first item to the end:

We're slicing from the second item (index 1 ) onward and then we're slicing up to, but not including, the second item. This made a new list with the first item ( watermelon ) moved to the end of the list.

Negative indexes work too

Note that negative indexes work the same way with slicing as with indexing.

Index -3 would give us the third to last item in a list:

Slicing from -3 onward would give us the last 3 items in the list:

Slicing up to index -3 (but not including it) would give us everything except for the last three items in the list:

Out-of-bounds slicing is allowed

Indexing and slicing are a little bit different in the way they treat indexes.

If we index past the end of a list, we'll see a traceback :

Indexing out-of-bounds will raise an exception. But slicing past the end of a list doesn't raise an exception:

An out-of-bounds slice just stops at the end of the list. The same applies to the beginning of the list:

This might look like a bug, but it can actually be a helpful feature. For example, if we wanted to get the first 3 items from a list, we could slice it:

And if there are fewer than 3 items in the list we're working with, we'll still get items! We'll just get every item that's in the list:

The slice step value

Slices have a start index and a stop index, but they also have an optional step value .

The start index defaults to 0 , the stop index defaults to the end of the list, and the optional step value, defaults to 1 :

If we change the step value to 2, we'll skip every other item:

If we change the step value to 3, it'll show us every third item:

The most common step value to see in a slice is -1 . A step value of -1 reverses the list:

Whenever a negative step value is given, the default meaning of start and stop change. With a negative step value, the start value will default to the last item in the list and the stop value will default to just before the beginning of the list.

Reversing a list is the most common use for the step value when slicing, though I typically prefer to use Python's built-in reversed function instead:

Slicing works on all sequences

It's important to note that slicing doesn't just work on lists. If we can index an object, we can probably slice it.

For example, we could use slicing to get the last 3 characters in a string :

You can slice pretty much any sequence in Python. A sequence is an object that can be indexed (from 0 to len(sequence)-1 ). Lists, tuples, and strings are all examples of sequences in Python.

The most common uses for slicing in Python

The most common uses of slicing in Python are...

Getting the first few items in a sequence

Getting the last few items in a sequence:

Or getting all items except for the first item, or all items except for the last item:

Those are not the only uses of slicing, but they are the most common.

Use slicing to get "slices" of sequences in Python

You can use slicing in Python to get portions of a list or any other sequence. Slicing is particularly great for getting the first few items, the last few items, everything but the first item, everything but the last item, or even reversing all the items in a sequence.

What comes after Intro to Python?

Intro to Python courses often skip over some fundamental Python concepts .

Sign up below and I'll explain concepts that new Python programmers often overlook .

Series: Data Structures

These screencasts are all about Python's core structures: lists, tuples, sets, and dictionaries.

To track your progress on this Python Morsels topic trail, sign in or sign up .

Sign up below and I'll share ideas new Pythonistas often overlook .

Definitions for colloquial Python terminology (effectively an unofficial version of the Python glossary).

A Comprehensive Guide to Slicing in Python

Follow me on Twitter to never miss my posts!

In Python, some objects like str s or list s can sliced . For example, you can get the first element of a list or a string with

Python uses square brackets ( [ and ] ) to access single elements of objects that can be decomposed into parts.

However, there is more to the inside of these square brackets than just accessing individual elements:

Negative Indexing

Perhaps you already know that you can use negative indices in Python like so:

Something like my_list[-1] represents the last element of a list, my_list[-2] represents the second last element and so on.

What if you want to retrieve more than one element from a list? Say you want everything from start to end except for the very last one. In Python, no problemo :

Or, what if you want every even element of your list, i.e. element 0 , 2 , etc.? For this we would need to go from the first element to the last element but skip every second item. We could write that as:

The slice Object

Behind the scenes, the index we use to access individual items of a list -like object consists of three values: (start, stop, step) . These objects are called slice objects and can be manually created with the built-in slice function.

We can check if the two are indeed the same:

Have a look at the graphic above. The letter P is the first element in our list, thus it can be indexed by 0 (see the numbers in the green boxes). The list has a length of 6 , and therefore, the first element can alternatively be indexed by -6 (negative indexing is shown in the blue boxes).

The numbers in the green and blue boxes identify single elements of the list. Now, look at the numbers in the orange boxes. These determine the slice indices of the list. If we use the slice’s start and stop , every element between these numbers is covered by the slice. Some examples:

That’s just an easy way to remember that the start value is inclusive and the end value is exclusive.

Sane defaults

Most of the time, you want to slice your list by

  • starting at 0
  • stopping at the end
  • stepping with a width of 1

Therefore, these are the default values and can be omitted in our : syntax:

Technically, whenever we omit a number between colons, the omitted ones will have the value of None .

And in turn, the slice object will replace None with

  • 0 for the start value
  • len(list) for the stop value
  • 1 for the step value

However, if the step value is negative, the None s are replaced with

  • -1 for the start value
  • -len(list) - 1 for the stop value

For example, "Python"[::-1] is technically the same as "Python"[-1:-7:-1]

Special Case: Copy

There is a special case for slicing which can be used as a shortcut, sometimes:

If you use just the default values, i.e. my_list[:] it will give you the exact same items:

The elements in the list are indeed the same. However, the list object is not. We can check that by using the id builtin:

Note that every slice operation returns a new object. A copy of our sequence is created when using just [:] .

Here are two code snippets to illustrate the difference:

Some often used examples:

Assignments

Understanding the loop.

Every slice object in Python has an indices method. This method will return a pair of ( start , end , step ) with which you could rebuild a loop equivalent to the slicing operation. Sounds complicated? Let’s have a closer look:

Let’s start with a sequence:

Then, we create a slice object. Let’s take every second element, i.e. [::2] .

Since we’re using None s, the slice object needs to calculate the actual index values based on the length of our sequence. Therefore, to get our index triple, we need to pass the length to the indices method, like so:

This will give us the triple (0, 6, 2) . We now can recreate the loop like so:

This accesses the same elements of our list as the slice itself would do.

Making Own Classes Sliceable

Python wouldn’t be Python if you could not use the slice object in your own classes. Even better, slices do not need to be numerical values. We could build an address book which sliceable by alphabetical indices.

Explanation

The get_addresses_by_first_letters method.

This method filters all addresses belonging to a name starting with any letter in the letters argument. First, we make the function case insensitive by converting our letters to uppercase. Then, we use a list comprehension over our internal addresses list. The condition inside the list comprehension tests if any of the provided letters matches the first letter of the corresponding name value.

The __getitem__ method

To make our AddressBook objects sliceable, we need to overwrite Python’s magic double underscore method __getitem__ .

At first, we check if our key is a str . This will be the case if we access our object with a single letter in square brackets like so: address_book["A"] . We can just return any addresses whose name starts with the given letter for this trivial case.

The interesting part is when the key is a slice object. For example, an access like address_book["A":"H"] would match that condition. First, we identify all letters alphabetically between A and H . The string module in Python lists all (latin) letters in in string.ascii_uppercase . We use a slice to extract the letters between the given letters. Note the +1 in the second slice parameter. This way, we ensure that the last letter is inclusive, not exclusive.

After we determined all letters in our sequence, we use the get_addresses_by_first_letters , which we already discussed. This gives us the result we want.

What's next?

Published Jan 31, 2022

I'm a software developer and tech trainer. Bas Steins on Twitter

  • Science with Python

Slice Assignment in Python – How Does It Work?

  • April 17, 2020 May 1, 2022

Today we’ll be talking about slice assignment in Python. It works with lists, which are mutable. We’ll also learn how to use slice assignment to mimic some of the most used list methods. This is not something that is crucial for mastering Python, but take it rather as an exercise. Normally you’d use the methods. That’s what they are for.

Lists are sequences, like tuples or strings, which means their elements are ordered and indexed. All sequences can be sliced. If we slice a string, we obtain a substring. If we slice a list, we obtain a sublist.

Here’s a video version. You can watch it first if you want.

And now, back to our main topic. First of all, what is slice assignment? Well, slice assignment in Python doesn’t work with strings or tuples, because they are immutable, but it works with lists. A list can be changed in place by assigning one or more elements to a slice. In other words, the whole slice is replaced by new elements.

Table of Contents

Examples of Slice Assignment in Python

The number of the elements may be equal to or different than the number of the elements in the slice.

slice assignment in Python

Here are some examples. In the most basic scenario you just replace a number of elements in the list by the same number of other elements:

slice assignment in python

Learn how to make beautiful GUI apps

in Python using the Kivy framework.

Comprehensive, for Kivy beginners, easy to follow.

Get the book here (PDF) or on Amazon:

ebook / paperback (black and white) / paperback (full color)

You can also replace a number of elements in the list by a smaller number of other elements. As a result, the list will shrink.

Naturally, the opposite is also possible. If you replace a number of elements in the list by a greater number of other elements, the list will expand:

slice assignment in python

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF) .

How to Use Slice Assignment to Imitate List Methods

This is more or less it, as far as slice assignment is concerned, but, here’s something for you to practice. Although in a real life scenario we’d use list methods to append, insert or delete list items, let’s see how this can be done with slice assignment.

Using Slice Assignment to Imitate the append Method

Let’s start with appending an item. To append an item is the same as to insert it at the end. Have a look:

slice assignment in python

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy .

Using Slice Assignment to Imitate the insert Method

Now let’s insert an item at the beginning:

Now let’s insert an item at index 4, so after the number 4:

Inserting multiple elements at the end, at the beginning and in the middle is just as simple. Here’s how we can insert 3 items at the beginning using slice assignment:

slice assignment in python

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare .

Using Slice Assignment to Delete List Items

Finally, how can you delete an item? You just need to assign an empty list to a slice. Suppose we want to delete the element at index 3, which is the number 4:

Share this:

Leave a reply cancel reply.

Python Slices Part 2: The Deep Cut

slice assignment in python

In this post, we're going to do a slightly deeper dive into slices in Python. If you need a refresher on the basics, be sure to check out our earlier post on the topic !

Without further ado, let's dive right in.

Slice Assignment

In the last post, we talked a lot about grabbing some slice of a sequence, but we can actually do a great deal more with slices.

One interesting thing we can do is replace some slice of a sequence with new values.

Here we take a slice of numbers which includes only the value at index 1. Remember that the stop index for slices is not inclusive .

We then use this slice as the left-hand side of an assignment. When we print numbers , we can see that it now reads [1, 2, 3] showing that the 3 at index 1 has been replaced.

One interesting thing to note is that we assigned another iterable, not just the integer 2 . We could have actually used a tuple or even a set here instead of a list:

However, assigning an integer would have raised a TypeError .

Assigning Multiple Values

As we have to assign some iterable type, it stands to reason we can assign multiple values in one go. That's absolutely correct:

However, what might surprise you is that we can assign an iterable of a different length to our slice.

It actually makes no difference how many items our iterable contains: we can even assign an empty list to some slice without issues. The items at the indexes defined in our slice are simply removed.

Zero Length Slices

We can also exploit the uneven assignment in other ways. For example, we can take an empty slice and use it to insert values in the middle of some sequence.

Remember that a slice like [1:1] is totally valid, but completely empty. It starts at index 1, and ends at index 1, but the stop value is not inclusive, so the value at index 1 is not part of the slice.

A slice like this therefore allows us to insert values at a given index without removing any values in the sequence.

Extended Slicing and Assignment

In the last article, we spoke about extended slicing, using a step value. We can still perform assignment on slices on this type, but there is a caveat. Unfortunately, if we specify any step value other than the default 1 , we can't use the asymmetrical assignment we've been talking about above. This includes a step of -1 .

As such, when we're using extended slice syntax, we need to be careful to match the number of values we want to replace.

The example above works just fine, because we assign 2 to index 1, and 4 to index 3. Everything matches.

On the other hand, this second example produces a ValueError :

Slice Objects and __getitem__

When we first started talking about slices, we began by introducing slice objects, and the slice(1, 2) syntax. We used this for a little while before moving on to the shorthand we've been using in the examples above.

We've actually seen a number of ways to take a slice of some sequence:

These are all absolutely identical in terms of functionality. If we printed any of a , b , or c , we'd get [2, 3] printed to the console.

However, this square brackets syntax is only a convenience. What's actually happening is this:

The slightly arcane looking __getitem__ is one of Python's many special methods, often called "dunder" (double underscore) methods.

What's interesting about this, is that we can use these special methods in our own classes, which means we can also provide slicing support for our own custom types.

__getitem__ actually accepts more than just slices. We could also pass in a single index to __getitem__ , which is exactly what happens when we do something like this: numbers[0] .

__getitem__ also has a counterpart called __setitem__ , which is called when we do slice assignment, or when we try to replace a value at a given index using subscript notation with single indexes:

Special methods are a large and relatively advanced topic, so don't worry if you're a little confused at this point. Special methods will be getting suitably special treatment in a future blog post, so stick around if you're interested in learning more about them!

  • In addition to using slices to grab a range of values from a sequence, we can also use slices to replace values in a sequence as part of an assignment operation.
  • We have to use an iterable type when assigning using a slice. This can be anything from list and tuples to sets.
  • Slice assignment can be asymmetrical: the length of the slice can be different to that of the iterable object we want to assign.
  • We can define a slice of zero length by specifying a start and stop value at the same index. We can use an empty slice to insert an arbitrary number of values at a given index.
  • When using extended slicing, any step value except 1 imposes some caveats on slice assignment. When using a different step size, the number of items we assign must match the number of items in the slice.
  • The subscript notation we use for slicing is actually shorthand for the __getitem__ and __setitem__ special methods. This is very useful, because it means we can define slicing behaviour for our own custom types.

I hope you learnt something new, and if you're looking to upgrade your Python skills even further, you might want to check out our Complete Python Course .

# Indexing and Slicing

# basic slicing.

For any iterable (for eg. a string, list, etc), Python allows you to slice and return a substring or sublist of its data.

Format for slicing:

  • start is the first index of the slice. Defaults to 0 (the index of the first element)
  • stop one past the last index of the slice. Defaults to len(iterable)
  • step is the step size (better explained by the examples below)

In addition, any of the above can be used with the step size defined:

Indices can be negative, in which case they're computed from the end of the sequence

Step sizes can also be negative, in which case slice will iterate through the list in reverse order:

This construct is useful for reversing an iterable

(opens new window) )

# Reversing an object

You can use slices to very easily reverse a str , list , or tuple (or basically any collection object that implements slicing with the step parameter). Here is an example of reversing a string, although this applies equally to the other types listed above:

Let's quickly look at the syntax. [::-1] means that the slice should be from the beginning until the end of the string (because start and end are omitted) and a step of -1 means that it should move through the string in reverse.

# Slice assignment

Another neat feature using slices is slice assignment. Python allows you to assign new slices to replace old slices of a list in a single operation.

This means that if you have a list, you can replace multiple members in a single assignment:

The assignment shouldn't match in size as well, so if you wanted to replace an old slice with a new slice that is different in size, you could:

It's also possible to use the known slicing syntax to do things like replacing the entire list:

Or just the last two members:

# Making a shallow copy of an array

A quick way to make a copy of an array (as opposed to assigning a variable with another reference to the original array) is:

Let's examine the syntax. [:] means that start , end , and slice are all omitted. They default to 0 , len(arr) , and 1 , respectively, meaning that subarray that we are requesting will have all of the elements of arr from the beginning until the very end.

In practice, this looks something like:

As you can see, arr.append('d') added d to arr , but copy remained unchanged!

Note that this makes a shallow copy, and is identical to arr.copy() .

# Indexing custom classes: getitem , setitem and delitem

This allows slicing and indexing for element access:

While setting and deleting elements only allows for comma seperated integer indexing (no slicing):

# Basic Indexing

Python lists are 0-based i.e. the first element in the list can be accessed by the index 0

You can access the second element in the list by index 1 , third element by index 2 and so on:

You can also use negative indices to access elements from the end of the list. eg. index -1 will give you the last element of the list and index -2 will give you the second-to-last element of the list:

If you try to access an index which is not present in the list, an IndexError will be raised:

# Slice objects

Slices are objects in themselves and can be stored in variables with the built-in slice() function. Slice variables can be used to make your code more readable and to promote reuse.

  • obj[start:stop:step]
  • slice(stop)
  • slice(start, stop[, step])

# Parameters

You can unify the concept of slicing strings with that of slicing other sequences by viewing strings as an immutable collection of characters, with the caveat that a unicode character is represented by a string of length 1.

In mathematical notation you can consider slicing to use a half-open interval of [start, end) , that is to say that the start is included but the end is not. The half-open nature of the interval has the advantage that len(x[:n]) = n where len(x) > = n , while the interval being closed at the start has the advantage that x[n:n+1] = [x[n]] where x is a list with len(x) >= n , thus keeping consistency between indexing and slicing notation.

← pyautogui module Plotting with Matplotlib →

Python Language

  • Getting started with Python Language
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • *args and **kwargs
  • Abstract Base Classes (abc)
  • Abstract syntax tree
  • Accessing Python source code and bytecode
  • Alternatives to switch statement from other languages
  • Asyncio Module
  • Attribute Access
  • Basic Curses with Python
  • Basic Input and Output
  • Binary Data
  • Bitwise Operators
  • Boolean Operators
  • Call Python from C#
  • Checking Path Existence and Permissions
  • ChemPy - python package
  • CLI subcommands with precise help output
  • Code blocks, execution frames, and namespaces
  • Collections module
  • Comments and Documentation
  • Common Pitfalls
  • Commonwealth Exceptions
  • Comparisons
  • Complex math
  • Conditionals
  • configparser
  • Connecting Python to SQL Server
  • Context Managers (“with” Statement)
  • Copying data
  • Create virtual environment with virtualenvwrapper in windows
  • Creating a Windows service using Python
  • Creating Python packages
  • Data Serialization
  • Data Visualization with Python
  • Database Access
  • Date and Time
  • Date Formatting
  • Defining functions with list arguments
  • Deque Module
  • Design Patterns
  • Difference between Module and Package
  • Distribution
  • Dynamic code execution with `exec` and `eval`
  • Exponentiation
  • Files & Folders I/O
  • Functional Programming in Python
  • Functools Module
  • Garbage Collection
  • getting start with GZip
  • Hidden Features
  • HTML Parsing
  • Immutable datatypes(int, float, str, tuple and frozensets)
  • Importing modules
  • Incompatibilities moving from Python 2 to Python 3
  • Indentation
  • Indexing and Slicing
  • Basic Slicing
  • Basic Indexing
  • Indexing custom classes: __getitem__, __setitem__ and __delitem__
  • Making a shallow copy of an array
  • Reversing an object
  • Slice assignment
  • Slice objects
  • Input, Subset and Output External Data Files using Pandas
  • Introduction to RabbitMQ using AMQPStorm
  • IoT Programming with Python and Raspberry PI
  • Iterables and Iterators
  • Itertools Module
  • JSON Module
  • kivy - Cross-platform Python Framework for NUI Development
  • Linked List Node
  • Linked lists
  • List comprehensions
  • List Comprehensions
  • List destructuring (aka packing and unpacking)
  • List slicing (selecting parts of lists)
  • Manipulating XML
  • Map Function
  • Math Module
  • Metaclasses
  • Method Overriding
  • Multidimensional arrays
  • Multiprocessing
  • Multithreading
  • Mutable vs Immutable (and Hashable) in Python
  • Neo4j and Cypher using Py2Neo
  • Non-official Python implementations
  • Operator module
  • Operator Precedence
  • Optical Character Recognition
  • Overloading
  • Pandas Transform: Preform operations on groups and concatenate the results
  • Parallel computation
  • Parsing Command Line arguments
  • Partial functions
  • Performance optimization
  • Pickle data serialisation
  • pip: PyPI Package Manager
  • Plotting with Matplotlib
  • Plugin and Extension Classes
  • Polymorphism
  • Processes and Threads
  • Property Objects
  • pyautogui module
  • PyInstaller - Distributing Python Code
  • Python and Excel
  • Python Anti-Patterns
  • Python concurrency
  • Python Data Types
  • Python HTTP Server
  • Python Lex-Yacc
  • Python Networking
  • Python Persistence
  • Python Requests Post
  • Python Serial Communication (pyserial)
  • Python Server Sent Events
  • Python speed of program
  • Python Virtual Environment - virtualenv
  • Queue Module
  • Raise Custom Errors / Exceptions
  • Random module
  • Reading and Writing CSV
  • Regular Expressions (Regex)
  • Secure Shell Connection in Python
  • Security and Cryptography
  • Similarities in syntax, Differences in meaning: Python vs. JavaScript
  • Simple Mathematical Operators
  • Sockets And Message Encryption/Decryption Between Client and Server
  • Sorting, Minimum and Maximum
  • Sqlite3 Module
  • String Formatting
  • String Methods
  • String representations of class instances: __str__ and __repr__ methods
  • Subprocess Library
  • tempfile NamedTemporaryFile
  • Templates in python
  • The __name__ special variable
  • The base64 Module
  • The dis module
  • The Interpreter (Command Line Console)
  • The locale Module
  • The os Module
  • The pass statement
  • The Print Function
  • Turtle Graphics
  • Unicode and bytes
  • Unit Testing
  • Unzipping Files
  • Usage of "pip" module: PyPI Package Manager
  • User-Defined Methods
  • Using loops within functions
  • Variable Scope and Binding
  • virtual environment with virtualenvwrapper
  • Virtual environments
  • Web scraping with Python
  • Web Server Gateway Interface (WSGI)
  • Webbrowser Module
  • Working around the Global Interpreter Lock (GIL)
  • Working with ZIP archives
  • Writing extensions
  • Writing to CSV from String or List

Python Language Indexing and Slicing Slice assignment

Fastest entity framework extensions.

Another neat feature using slices is slice assignment. Python allows you to assign new slices to replace old slices of a list in a single operation.

This means that if you have a list, you can replace multiple members in a single assignment:

The assignment shouldn't match in size as well, so if you wanted to replace an old slice with a new slice that is different in size, you could:

It's also possible to use the known slicing syntax to do things like replacing the entire list:

Or just the last two members:

Got any Python Language Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

Python List Slicing

To access a range of items in a list , you need to slice a list. One way to do this is to use the simple slicing operator :

With this operator you can specify where to start the slicing, where to end and specify the step.

Slicing a List

If L is a list, the expression L [ start : stop : step ] returns the portion of the list from index start to index stop , at a step size step .

Python List Slicing - Syntax

Basic Example

Here is a basic example of list slicing.

Python List Slicing Illustration

Note that the item at index 7 'h' is not included.

Slice with Negative Indices

You can also specify negative indices while slicing a list.

Python List Slicing - Negative Indices

Slice with Positive & Negative Indices

You can specify both positive and negative indices at the same time.

Specify Step of the Slicing

You can specify the step of the slicing using step parameter. The step parameter is optional and by default 1.

Python List Slicing - Specifying Step Size

Negative Step Size

You can even specify a negative step size.

Slice at Beginning & End

Omitting the start index starts the slice from the index 0. Meaning,  L[:stop]  is equivalent to  L[0:stop]

Whereas, omitting the stop index extends the slice to the end of the list. Meaning, L[start:]  is equivalent to  L[start:len(L)]

Reverse a List

You can reverse a list by omitting both start and stop indices and specifying a step as -1.

Modify Multiple List Values

You can modify multiple list items at once with slice assignment . This assignment replaces the specified slice of a list with the items of assigned iterable .

Insert Multiple List Items

You can insert items into a list without replacing anything. Simply specify a zero-length slice.

You can insert items into the middle of list by keeping both the start and stop indices of the slice same.

Delete Multiple List Items

You can delete multiple items out of the middle of a list by assigning the appropriate slice to an empty list.

You can also use the del statement with the same slice.

Clone or Copy a List

When you execute new_List = old_List , you don’t actually have two lists. The assignment just copies the reference to the list, not the actual list. So, both new_List and old_List refer to the same list after the assignment.

You can use slicing operator to actually copy the list (also known as a shallow copy ).

How to Use Slice Assignment in NumPy?

NumPy slice assignment allows you to use slicing on the left-hand side of an assignment operation to overwrite a specific subsequence of a NumPy array at once. The right side of the slice assignment operation provides the exact number of elements to replace the selected slice. For example, a[::2] = [...] would overwrite every other value of NumPy array a .

Here’s a minimal example of slice assignment:

The NumPy slice assignment operation doesn’t need the same shape on the left and right side because NumPy will use broadcasting to bring the array-like data structure providing the replacement data values into the same shape as the array to be overwritten.

The next example shows how to replace every other value of a 1D array with the same value. The left and right operands don’t have the same array shape—but NumPy figures it out through broadcasting .

For 2D arrays, you can use the advanced slice notation —selection comma-separated by axis—to replace whole columns like so:

Let’s dive into a practical example about NumPy slice assignments from my Python One-Liners book next. Take your time to study it and watch the explainer video to polish your NumPy slicing skills once and for all.

Practical Example Slice Assignment NumPy

Python One-Liner | Data Science 5 | NumPy Slice Assignment

Real-world data is seldomly clean: It may contain errors because of faulty sensor, or it may contain missing data because of damaged sensors. In this one-liner example, you learn about how to quickly handle smaller cleaning tasks in a single line of code .

Say, you have installed a temperature sensor in your garden to measure temperature data over a period of many weeks. Every Sunday, you uninstall the temperature sensor from the garden and take it in your house to digitize the sensor values. Now, you realize that the Sunday sensor values are faulty because they partially measured the temperature at your home and not at the outside location.

In this mini code project, you want to “clean” your data by replacing every Sunday sensor value with the average sensor value of the last seven days. But before we dive into the code, let’s explore the most important concepts you need as a basic understanding.

Examples Slice Assignment NumPy

In NumPy’s slice assignment feature, you specify the values to be replaced on the left-hand side of the equation and the values that replace them on the right-hand side of the equation.

Here is an example:

The code snippet creates an array containing 16 times the value 4. Then we use slice assignment to replace the 15 trailing sequence values with the value 16. Recall that the notation a[start:stop:step] selects the sequence starting at index “start”, ending in index “stop” (exclusive), and considering only every “step”-th sequence element. Thus, the notation a[1::] replaces all sequence elements but the first one.

This example shows how to use slice assignment with all parameters specified. An interesting twist is that we specify only a single value “16” to replace the selected elements. Do you already know the name of this feature?

Correct, broadcasting is the name of the game! The right-hand side of the equation is automatically transformed into a NumPy array. The shape of this array is equal to the left-hand array.

Before we investigate how to solve the problem with a new one-liner, let me quickly explain the shape property of NumPy arrays. Every array has an associated shape attribute (a tuple ). The i-th tuple value specifies the number of elements of the i-th axis. Hence, the number of tuple values is the dimensionality of the NumPy array.

Read over the following examples about the shapes of different arrays:

We create three arrays a , b , and c .

  • Array a is 1D, so the shape tuple has only a single element.
  • Array b is 2D, so the shape tuple has two elements.
  • Array c is 3D, so the shape tuple has three elements.

Problem Formulation

This is everything you need to know to solve the following problem:

Given an array of temperature values, replace every seventh temperature value with the average of the last seven days.

Take a guess : what’s the output of this code snippet?

First, the puzzle creates the data matrix “ tmp ” with a one-dimensional sequence of sensor values. In every line, we define all seven sensor values for seven days of the week (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday).

Second, we use slice assignment to replace all the Sunday values of this array. As Sunday is the seventh day of the week, the expression “ tmp[6::7] ” selects the respective Sunday values starting from the seventh element in the sequence (again: the Sunday sensor value).

Third, we reshape the one-dimensional sensor array into a two-dimensional array with seven columns. This makes it easier for us to calculate the weekly average temperature value to replace the Sunday data. Note that the dummy shape tuple value -1 (in “ tmp.reshape((-1,7)) ”) means that the number of rows ( axis 0 ) should be selected automatically. In our case, it results in the following array after reshaping :

It’s one row per week and one column per weekday.

Now we calculate the 7-day average by collapsing every row into a single average value using the np.average() function with the axis argument: axis=1 means that the second axis is collapsed into a single average value. This is the result of the right-hand side of the equation:

After replacing all Sunday sensor values, we get the following final result of the one-liner:

This example is drawn from my Python One-Liners book:

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills . You’ll learn about advanced Python features such as list comprehension , slicing , lambda functions , regular expressions , map and reduce functions, and slice assignments .

You’ll also learn how to:

  • Leverage data structures to solve real-world problems , like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array , shape , axis , type , broadcasting , advanced indexing , slicing , sorting , searching , aggregating , and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups , negative lookaheads , escaped characters , whitespaces, character sets (and negative characters sets ), and greedy/nongreedy operators
  • Understand a wide range of computer science topics , including anagrams , palindromes , supersets , permutations , factorials , prime numbers , Fibonacci numbers, obfuscation , searching , and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined , and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

Where to Go From Here?

Do you love data science? But you struggle to get everything together and develop a good intuition about the NumPy library?

To help you improving your code understanding speed in NumPy, I co-authored a brand-new NumPy book based on puzzle-based learning. Puzzle-based learning is a new, very practical approach to learning to code — based on my experience of teaching more than 60,000 ambitious Python coders online.

Get your “ Coffee Break NumPy ” now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer , and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

VIDEO

  1. Slice en Python 3

  2. Slicing in Python #python #beginners #slice #jupiter

  3. To access items of array in range (Slice arrays) in python

  4. Problem in Slice Method

  5. Slice Method in Python #gurukula #python #datatype #slicing

  6. How To Slice A Dictionary In Python 2024

COMMENTS

  1. python

    When you specify a on the left side of the = operator, you are using Python's normal assignment, which changes the name a in the current context to point to the new value. This does not change the previous value to which a was pointing.. By specifying a[0:2] on the left side of the = operator, you are telling Python you want to use slice assignment.Slice assignment is a special syntax for ...

  2. Understanding Python's slice assignment

    Basic syntax. In order to understand Python's slice assignment, you should at least have a decent grasp of how slicing works. Here's a quick recap: [ start_at: stop_before: step] Where start_at is the index of the first item to be returned (included), stop_before is the index of the element before which to stop (not included) and step is the ...

  3. slice

    Python slicing is a computationally fast way to methodically access parts of your data. In my opinion, to be even an intermediate Python programmer, it's one aspect of the language that it is necessary to be familiar with. ... In addition, when using slice notation in assignments, the length of the slice assignments do not need to be the same ...

  4. Python Slicing

    How to Slice an Array in Python. Let's say you want to slice a portion of this array and assign the slice to another variable. You can do it using colons and square brackets. The syntax looks like this: array[start:stop:step] The start index specifies the index that the slicing starts from. The default is 0.

  5. Python Slice Assignment

    Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence. Simply select the slice you want to replace on the left and the values to replace it on the right side of the equation. For example, the slice assignment list[2:4] = [42, 42] replaces the list elements with index 2 and 3 with the value 42.

  6. Python Slicing in Depth

    blue. How it works. First, create a slice object whose start is 0, stop is 4, and step is 2. Second, return a tuple of indices of the slice of the sequence whose length is the length of the colors list. Third, pass the result tuple to the range function to select elements from the colors list.

  7. Understanding Python's slice assignment

    Slice assignment has the same syntax as slicing a list with the only exception that it's used on the left-hand side of an expression instead of the right-hand side. Since slicing returns a list, slice assignment requires a list (or other iterable).

  8. Slicing Lists in Python: A Comprehensive How-To Guide

    List slicing in Python is an operation that allows you to retrieve a range of items from a list by specifying start and end indices. It returns a new list containing the extracted elements. The basic syntax for slicing a list is: new_list = original_list [start:end] Here: original_list is the list you want to slice.

  9. List slicing in Python

    With Python's slicing syntax, the first item is the start index, and the second item is the stop index.The start index is inclusive, but the stop index is exclusive, meaning Python stops just before the stop index.. So we got the items at index 1 and index 2 because we stopped just before index 3.. Default slice start/stop values. The start and stop values are both optional when slicing.

  10. How to Slice Sequences in Python

    And since lists are mutable in Python, we saw how we can use slice assignment to change portions of our lists. We then saw the differences between slicing a list and slicing a string, in that slicing a list returns a copy of that list, but slicing a string returns a reference to the original string object.

  11. A Comprehensive Guide to Slicing in Python

    The interesting part is when the key is a slice object. For example, an access like address_book["A":"H"] would match that condition. First, we identify all letters alphabetically between A and H. The string module in Python lists all (latin) letters in in string.ascii_uppercase. We use a slice to extract the

  12. Slice Assignment in Python

    Today we'll be talking about slice assignment in Python. It works with lists, which are mutable. We'll also learn how to use slice assignment to mimic some of the most used list methods. This is not something that is crucial for mastering Python, but take it rather as an exercise. Normally you'd use the methods. That's what they are for.

  13. Python Slices Part 2: The Deep Cut

    When using extended slicing, any step value except 1 imposes some caveats on slice assignment. When using a different step size, the number of items we assign must match the number of items in the slice. The subscript notation we use for slicing is actually shorthand for the __getitem__ and __setitem__ special methods. This is very useful ...

  14. Slice Assignment in Python

    In this Python video we'll be talking about slice assignment. It works with lists, which are mutable. We'll also learn how to use slice assignment to mimic s...

  15. Python

    Let's quickly look at the syntax. [::-1] means that the slice should be from the beginning until the end of the string (because start and end are omitted) and a step of -1 means that it should move through the string in reverse. # Slice assignment Another neat feature using slices is slice assignment. Python allows you to assign new slices to replace old slices of a list in a single operation.

  16. Understanding Python's slice notation

    Understanding Python's slice assignment. Learn everything you need to know about Python's slice assignment with this handy guide. Python · June 12, 2021 What is the difference between list.sort() and sorted() in Python? Learn the difference between Python's built-in list sorting methods and when one is preferred over the other. Python · June ...

  17. Python Language Tutorial => Slice assignment

    Example #. Example. Another neat feature using slices is slice assignment. Python allows you to assign new slices to replace old slices of a list in a single operation. This means that if you have a list, you can replace multiple members in a single assignment: lst = [1, 2, 3] lst[1:3] = [4, 5] print(lst) # Out: [1, 4, 5] The assignment shouldn ...

  18. Python List Slicing

    Learn to slice a list with positive & negative indices in Python, modify insert and delete multiple list items, reverse a list, copy a list and more. ... So, both new_List and old_List refer to the same list after the assignment. You can use slicing operator to actually copy the list (also known as a shallow copy). L1 = ['a', 'b', 'c', 'd', 'e ...

  19. How to Use Slice Assignment in NumPy?

    In NumPy's slice assignment feature, you specify the values to be replaced on the left-hand side of the equation and the values that replace them on the right-hand side of the equation. Here is an example: import numpy as np. a = np.array( [4] * 16) print(a) # [4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4] a[1::] = [16] * 15.

  20. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  21. python

    Slice assignment takes an iterable on the right-hand side, and replaces the elements of the slice with the objects produced by the iterable. In Python, strings are iterable: iterating over a string yields its characters. Thus. L1[0:1] = 'cake'. replaces the first element of L1 with the individual characters of 'cake'.