0

I have a question about 2 lines of code - from my thinking point of view it should be the same, but i get different outputs for those 2 lines.

Can someone explain me why?

max(week[-1] for week in calendar.monthcalendar(year,month))
max(calendar.monthcalendar(year,month)[-1])

year = 2021 and month = 3

For the first line I get the right output 28th which was the sunday. For the second line I get 31, which basically just is the last number. week[-1] from monthcalendar should be the last array or not? Which in this case would be [29,30,31,0,0,0,0] so the max from it should be 31

max(week for week in calendar.monthcalender(year,month))
max(week[-1] for week in calendar.monthcalendar(year,month))

Also this 2 lines - the first gives me an array [29,30,31,0,0,0,0] and the second gives me a single number 28 and I don't get why? shouldnt the first return 31 and the second 28?

Dominik Lemberger
  • 2,287
  • 2
  • 21
  • 33

1 Answers1

3

I would suggest to review parts of the data to see what is going on:

The first max(week[-1] for week in calendar.monthcalendar(year,month)) loops over the week lists of the calendar. The output of the for loop is: 7, 14, 21, 28, 0: printing each last day of the week. Hence max returns 28 as it is the max of this.

The second max(calendar.monthcalendar(year,month)[-1]) takes the last week of the month [29, 30, 31, 0, 0, 0, 0]. Hence max returns 31.

The third max(week for week in calendar.monthcalender(year,month)) gives the biggest list of the monthcalendar. See Comparing two lists using the greater than or less than operator why the last list is returned.

The fourth is the same as the first.

rfkortekaas
  • 6,049
  • 2
  • 27
  • 34