Guest

Getting the first and last item in a python for loop

By: a guest on Jan 28th, 2012  |  syntax: None  |  size: 0.79 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. from calendar import Calendar
  2.  
  3. cal = Calendar(6)
  4. month_dates = cal.itermonthdates(year, month)
  5. for date in month_dates:
  6.     if (is first item):     # this is fake
  7.         month_start = date
  8.     if (is last item):      # so is this
  9.         month_end = date
  10.        
  11. from calendar import Calendar, SUNDAY
  12.  
  13. cal = Calendar(SUNDAY)
  14. month_dates = list(cal.itermonthdates(year, month))
  15.  
  16. month_start = month_dates[0]
  17. month_end = month_dates[-1]
  18.        
  19. for i, date in enumerate(month_dates):
  20.     if i == 0:
  21.         month_start = date
  22.  
  23. month_end = date
  24.        
  25. month_dates = cal.itermonthdates(year, month)
  26. month_start = month_dates.next()
  27. for month_end in month_dates: pass # bletcherous
  28.        
  29. month_dates = cal.itermonthdates(year, month)
  30. month_start = month_dates.next()
  31. for date in month_dates:
  32.     pass
  33. month_end = date