0

Why for example when slicing a list with square brackets in this way

spam = [1, 2, 3]

When we print(spam[0:2]) the 3 is not typed while the index of that is 2?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
moh80s
  • 763
  • 1
  • 7
  • 21

2 Answers2

2

This style of indexing is just very beautiful and comfortable. There're lots of cases where this can be useful. The easiest one is when you have to do something on two halves of an array:

spam = [1, 2, 3, 4, 5]
center_index = len(spam) / 2
func(spam[center_index:])
func(spam[:center_index])

In this example, you don't have to think about +1/-1

Kolay.Ne
  • 1,345
  • 1
  • 8
  • 23
0

Because Python slicing is inclusive @ start and exclusive @ the end

Mohamed ElKalioby
  • 1,908
  • 1
  • 12
  • 13