How to use index to access the element in a Python List
All elements in a list is numbered and we can access element by the numbers. The number starts from zero.
From the code above we can see that the elements in accessed by the index.
If the number is negative Python counts the index from right of the list. -1 is the right most element.
li = ["a", "b", "c", "z", "example"] print li print li[-1] print li[-3]
The code above generates the following result.
Print out a date, given year, month, and day as numbers
months = [ # from w ww . jav a 2s . c om 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] # A list with one ending for each number from 1 to 31 endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th'] + ['st'] year = 2013 month = 5 day = 28 month_number = int(month) day_number = int(day) # Remember to subtract 1 from month and day to get a correct index month_name = months[month_number-1] ordinal = day + endings[day_number-1] print month_name + ' ' + ordinal + ', ' + year