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

Example

Slicing

To take the first two slices, youג€™d use:

1
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.

List slice

Create a list of persons. Weג€™ll use the slicing technique to get the first two persons in the list.

1
2
3
4
5
#!/usr/bin/python
persons = [ "John", "Marissa", "Pete", "Dayton" ]

slice = persons[0:2]
print(slice)

This outputs the slice:

python slice

String slicing

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.

1
2
3
destination = "summer holiday at beach"
mySlice = destination[0:6]
print(mySlice)

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

Try the exercises below

  1. Take a slice of the list below:
    pizzas = [“Hawai”,”Pepperoni”,”Fromaggi”,”Napolitana”,”Diavoli”]

  2. Given the text 'Hello World', take the slice 'World'