It works but why the need to alter the index by subtracting 1

Viewed 38

Novice here, Question, why do I need to subtract one to reference the correct indice for month_name and ordinal.

This prints out a date, given year, month, and day as numbers from inputs.

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 
          'August', 'September', 'October', 'November', 'December']

endings = ['st', 'nd', 'rd'] + 17 * ['th'] \
        + ['st', 'nd', 'rd'] + 7 * ['th'] \
        + ['st']

year = input('Year: ')

month = input('Month (1-12: ')

day = input('Day (1-31): ')

month_number = int(month) 

day_number = int(day)    

month_name = months[month_number-1]  #Although it works, what's the logic.
ordinal = day + endings[day_number-1 #Although it works, what's the  logic.

print(month_name , ' ' + ordinal , ', ' + year)
3 Answers

Because python is zero-indexed. Which means the first element is 0 rather than 1

So for example:

In your code, March would be given by the user as 3 (1 Jan, 2 Feb, 3 March)

But in your python list, March would be at 2nd place (0 Jan, 1 Feb, 3 March)

Most of the coding languages are 0 indexed and for python everything that is iterable is 0 indexed as well

Most programming languages have lists which are zero-indexed.

For example:

list = ["one", "two", "three"]

print(list[0])  # one
print(list[2])  # three

Simply because the Python index start from 0.

If you define a list as the following:

sample_list = ["Jan", "Feb", "Mar"]
print(sample_list[0])

You will get Jan printed instead of Feb.

Similarly, Feb 's index is 1 and Mar 's is 2.

Related