Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Slice Lists in Python

    Will ButtonWill Button

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

    pythonpython
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss