3
pizzas  = ["hawai","salame","vegetable","capriciosa","new york"]
for pizza in pizzas:
    print("I like " + pizza.title() + " pizza!")
print("\n" + "The first three pizzas in the list are: " + str(pizzas[0:3]))
print("\n" + "The last three pizzas in the list are: " + str(pizzas[-1:-3]))

I get:

I like Hawai pizza!
I like Salame pizza!
I like Vegetable pizza!
I like Capriciosa pizza!
I like New York pizza!

The first three pizzas in the list are: ['hawai', 'salame', 'vegetable']

The last three pizzas in the list are: []

and I'm puzzled. Isn't -1 indicating the last element in the list ? I'm indexing [start:stop] so shouldn't it print my the last 3 items ? What am I doing wrong ?

gyre
  • 16,369
  • 3
  • 37
  • 47
cyzczy
  • 197
  • 1
  • 2
  • 11

2 Answers2

11

You should be using pizzas[-3:] instead, so that your start is the third element from the end of the list and your end is the very end of the list.

pizzas  = ["hawai","salame","vegetable","capriciosa","new york"]

for pizza in pizzas:
    print("I like " + pizza.title() + " pizza!")

print("\nThe first three pizzas in the list are: " + str(pizzas[:3]))
print("\nThe last three pizzas in the list are: " + str(pizzas[-3:]))
gyre
  • 16,369
  • 3
  • 37
  • 47
  • thank you to both of you. Is there any specific reason why it didn't work the way I wrote ? – cyzczy Apr 19 '17 at 18:01
  • 3
    Yes; if you start at index `-1` and end at `-3`, your `start` value is actually greater (further along in the string) than `end`. When slicing, `start` should always be less than `end`. The other issue is that, even reversing those two indexes and using `pizzas[-3:-1]`, ending at `-1` will actually not include the last item. The `start` index is "inclusive", while `end` is "exclusive." Fortunately, Python has a shorthand for going up until the very end of the list, which is simply to omit the `end` argument when slicing. You can do the same thing with `start` and let it default to zero. – gyre Apr 19 '17 at 18:04
6

The default step is 1, so going from -1 to -3 with a step of one returns an empty slice. You could explicitly indicate the step as -1, but this reverses the order of the items:

>>> pizzas[-1:-3:-1] 
['new york', 'capriciosa'] # -3 excluded

However, to get the last three items, what you want is pizza[-3:]

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139