0

I'm trying to create a list with the number of days of each month between 1901 and 2000, but I can't manage to change the values properly. Here's my code:

year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
period = [year] * 100

for i in range(1901, 2001):
    if i % 4 == 0 and i % 100 != 0:
        period[i-1901][1] = 29

period[99][1] = 29
print period

When I execute it, the list that I get has 29 as second entry for every year, which I obviously do not want. What am I doing wrong? Thanks.

Hari Seldon
  • 141
  • 10
  • Minor comment on your logic but your code will assume 2000 wasn't a leap year but it was as all years divisible by 400 are. – FinlayL Aug 19 '14 at 15:55

1 Answers1

2
period = [year] * 100

This creates a list containing 100 references to the same year object. Modifying one will modify all of them.

One possible solution is to use slicing to create new copies of year.

period = [year[:] for _ in range(100)]
Kevin
  • 74,910
  • 12
  • 133
  • 166