A slice can be taken from a string or list, just as you can take a slice from a pizza.
To take the first two slices, you’d use:

slice = pizza[0:2]

Why 0? 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.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Example

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

#!/usr/bin/python
persons = [ "John", "Marissa", "Pete", "Dayton" ]

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

This outputs the slice:

python slice

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”

Download answers