Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Print number of leap years from given list of years
A leap year occurs every four years and has 366 days instead of 365. The extra day is added to February, making it 29 days. Python provides several ways to identify and count leap years from a list of years.
A year is a leap year if it's divisible by 4, but if it's divisible by 100, it must also be divisible by 400 to be a leap year.
Using Lambda Function with Calendar Module
The calendar.isleap() function with filter() and lambda provides a concise solution ?
import calendar
# List of years to check
years = [1998, 1987, 1996, 1972, 2003, 2000, 2100]
# Filter leap years using lambda function
leap_years = list(filter(lambda year: calendar.isleap(year), years))
print("Leap years from the list are:", leap_years)
print("Total number of leap years:", len(leap_years))
Leap years from the list are: [1996, 1972, 2000] Total number of leap years: 3
Using Conditional Statement
Manual leap year calculation using the standard leap year rules ?
# List of years to check
years = [1998, 1987, 1996, 1972, 2003, 2000, 2100]
leap_years = []
# Check each year using leap year logic
for year in years:
if ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)):
print(f"Leap year from the list is: {year}")
leap_years.append(year)
print("Total number of leap years:", len(leap_years))
Leap year from the list is: 1996 Leap year from the list is: 1972 Leap year from the list is: 2000 Total number of leap years: 3
Using Calendar Module with Loop
A straightforward approach using calendar.isleap() in a loop ?
import calendar
# List of years to check
years = [1998, 1987, 1996, 1972, 2003, 2000, 2100]
leap_years = []
# Check each year using calendar.isleap()
for year in years:
if calendar.isleap(year):
print(f"Leap year from the list is: {year}")
leap_years.append(year)
print("Total number of leap years:", len(leap_years))
Leap year from the list is: 1996 Leap year from the list is: 1972 Leap year from the list is: 2000 Total number of leap years: 3
Comparison
| Method | Code Length | Readability | Performance |
|---|---|---|---|
| Lambda + Filter | Short | Medium | Good |
| Conditional Statement | Medium | High | Fast |
| Calendar Module | Medium | High | Good |
Conclusion
Use calendar.isleap() for simplicity and reliability. The conditional statement approach is fastest but requires understanding leap year rules. Lambda with filter provides concise functional programming style.
