1
#!/usr/bin/python


list2 = ['Bangalore','Cochin','Trivandrum','Auckland','Seoul','Los Angeles']

list2[5] = 'Hamilton'

list2.append('Sydney')
list2.append('San Jose')
list2.append('Amsterdam')

print "Cities = ",list2[0:(len(list2) - 1)]

print "Cities = ",list2[0:(len(list2))]

The first print statement does not print the last element in the list.The second print statement does print all the elements in the list without an out of bounds errors.From the documentation I understand len() simply returns the number of elements in the list.Then why is the last index not len(list) - 1

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
liv2hak
  • 14,472
  • 53
  • 157
  • 270

2 Answers2

7

List slicing never throws an out-of-bounds error:

list2[0:1234567890]

is legal, as is

list2[-1:-1]

Note that when slicing, the upper bound is not included in the slice:

>>> list2[0:1]
['Bangalore']
>>> list2[0:0]
[]

so the slice list2[0:len(list2)] contains exactly the same elements as list2 without slicing, but does return a new list.

Some other remarks:

  • If you omit the start value, it defaults to 0, and the end value, if omitted, defaults to the length of the list. Thus, list2[0:len(list2)] can be written as list2[:].

  • negative values count from the end. list2[:len(list2)-1] can be written as list2[:-1].

Blckknght
  • 100,903
  • 11
  • 120
  • 169
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks for the detailed explanation.as you would have guessed I am new to python. :) – liv2hak May 22 '13 at 22:33
  • @Blckknght: Yeah, it appears that Chrome C&P sometimes produces non-breaking spaces, and I don't always notice it when it does. Thanks for the correction! – Martijn Pieters May 22 '13 at 22:52
3

Because the upper bound is not inclusive. That means if your list has 1 element, you need to put 1, not 0, to include it in the slice. list[0:0] is effectively an empty slice, and if the upper bound was inclusive, there would be no way to get an empty slice. To get a slice with the first element only, you'll need list[0:1] instead.

(I'm using a list with just 1 element because it's super simple to understand. It obviously holds for lists with more items.)

zneak
  • 134,922
  • 42
  • 253
  • 328