Slice Lists in Python

Will Button
InstructorWill Button
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

Slicing allows you to extract one or more values from a list. Learn how to accomplish this in Python in this lesson.

Let me show you how list slicing works in Python. Slicing is a way to return a copy of a list with specified elements. You slice a list by providing the start and end of where you'd like the slice to be.

In this example, we're slicing from two to five and the important thing to remember is lists are indexed starting at zero, so index item two is the third element in the list. The end point of our slice is the fifth index item in the list, which is the number six, but in Python the end point is not included. The five is the last number that we get in our copied list.

If you don't specify an end point, it continues on to the end of the list, and if you don't provide a start point, it starts at the beginning of the list. You can use negative numbers to specify backwards from the end of the list. In this example it's going to go to the fourth index from the end and then return to the end of the list.

You can also use list slicing to replace certain parts of the list. If we specify A, two through five, and then provide a new list with the values we'd like to replace it with, when we print out the list we can see that the values that matched that slice were replaced with the values we provided.

egghead
egghead
~ 38 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today