A slice can be taken from a string or list, just as you can take a slice from a pizza.
If you have a variable, be it a list or a string, that you want a part of, you don’t have to define it all over again.
You can get a copy of the variable, which is the whole or a subset of the original variable. This concept is known as slicing.
Related course: Complete Python Programming Course & Exercises
To take the first two slices, you’d use:
slice = pizza[0:2]
The variable slice will now contain a copy of pizza, but only part of it. This is expressed using the brackets, the first number is the start and the number after the colon is the end.
Why does it start with zero?
Python starts numbering of string and list elements from zero, not one.
In this case we took a slice from the list pizza, the output is stored into a new variable.
If you want you can pass it directly to the print function.
Create a list of persons. We’ll use the slicing technique to get the first two persons in the list.
persons = [ "John", "Marissa", "Pete", "Dayton" ]
slice = persons[0:2]
This outputs the slice:
A string can be sliced too. This is done in exactly the same way, but the main differnece is that it won’t return a number of items, but simply a new string.
destination = "summer holiday at beach"
If you are a beginner, then I highly recommend this book.
Try the exercises below
Take a slice of the list below:
pizzas = [“Hawai”,”Pepperoni”,”Fromaggi”,”Napolitana”,”Diavoli”]
Given the text “Hello World”, take the slice “World”