[Tutor] Final review

Alan Gauld alan.gauld at btinternet.com
Tue May 6 19:36:21 CEST 2014


On 06/05/14 04:43, Scott Dunning wrote:
> I have another question.  I don’t understand why below would give an error?
>
>>>> greeting = 'Hello World'
>>>> greeting [len(greeting)]


Because list indexing starts at zero but len() returns the actual 
length. So the last element of a list is

mylist[len(mylist)-1]

or, more simply:

mylist[-1]

Aside:
len() does work with range() and slicing so you can write

myList[:len(mylist)]

to get a copy of your list...

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list