Check out a free preview of the full Practical Guide to Python course

The "Slicing" Lesson is part of the full, Practical Guide to Python course featured in this preview video. Here's what you'd learn in this lesson:

Nina demonstrates how to use slicing to return a subset from a larger list. Slicing can be used on any data type that maintains an order, such as a string, list, or tuple.

Preview
Close

Transcript from the "Slicing" Lesson

[00:00:00]
>> Slicing in Python is an easy way to create sub lists from larger lists. So we saw how easy it is to access an item by index. We can also ask for a range at an index with splicing. So let's say I had a string here. If I got the value at 0, that would just be the letter H.

[00:00:36]
I can ask for a slice of the string by passing in the starting point, followed by a colon, and then the ending point. So that's just going to return everything from index 7 and onwards. You can also do lopsided slicing. So if this first value was not present, that is a shortcut saying start at 0.

[00:01:11]
If we have a value on the left-hand side, but not on the right-hand side. That's a shortcut that says, go all the way to the end of the string or the end of the sequence. So that's a little bit of shortcut syntax that you might see. If you quickly want to create a full copy of a string or a list, you can omit both the start and the end.

[00:01:41]
And that will return just a full copy from the beginning to the end. You can also have negative indexing. So if I wanted just the last character, I could pass in negative 1 and that says, go back one from the end. You can also do a little bit of reversing here with negative indexing.

[00:02:05]
So I can say from negative 10 to negative 7, and that will get the values from the 10th index from last to the 7th index from last. If I switched the order of these, oops, then you would not see anything at all. Because that's asking for a slice that doesn't exist.

[00:02:34]
You can also pass in a stride or a step as well. That will be a optional third argument here. I'm not going to cover it. You generally won't see it too much out there in code in the wild, but in case you do you know what to look for.

[00:02:53]
There's another optional exercise on the zip function that lets you take two different lists and combine them together to form some data structures that might help you translate into a dictionary if needed. Some more advanced concept if that's something that you find interesting, I recommend going back and checking that out.

[00:03:16]
But we're gonna talk about working with files.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now