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
Create a list of persons. We’ll use the slicing technique to get the first two persons in the list.
This outputs the slice:
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”