 Open in App
Not now

# Python | Print number of leap years from given list of years

• Last Updated : 02 Jan, 2023

The problem of finding leap year is quite generic and we might face the issue of finding the number of leap years in given list of years. Let’s discuss certain ways in which this can be performed.

Method #1: Using Iteration
Check whether year is a multiple of 4 and not multiple of 100 or year is multiple of 400.

## Python3

 `# Python code to finding number of``# leap years in list of years.` `# Input list initialization``Input` `=` `[``2001``, ``2002``, ``2003``, ``2004``, ``2005``, ``2006``,``         ``2007``, ``2008``, ``2009``, ``2010``, ``2011``, ``2012``]` `# Find whether it is leap year or not``def` `checkYear(year):``    ``return` `(((year ``%` `4` `=``=` `0``) ``and``             ``(year ``%` `100` `!``=` `0``)) ``or``             ``(year ``%` `400` `=``=` `0``))`` ` `# Answer Initialization``Answer ``=` `0` `for` `elem ``in` `Input``:``    ``if` `checkYear(elem):``        ``Answer ``=` `Answer ``+` `1` `# Printing``print``(``"No of leap years are:"``, Answer)`

Output:

`No of leap years are: 3`

Time Complexity: O(n) where n is the size of the list.

Auxiliary Space: O(1)

Method #2: Using calendar

## Python3

 `# Python code to finding number of``# leap years in list of years.` `# Importing calendar``import` `calendar` `# Input list initialization``Input` `=` `[``2001``, ``2002``, ``2003``, ``2004``, ``2005``,``         ``2006``, ``2007``, ``2008``, ``2009``, ``2010``]` `# Using calendar to find leap year``def` `FindLeapYear(``Input``):``    ``ans ``=` `0``    ``for` `elem ``in` `Input``:``        ``if` `calendar.isleap(``int``(elem)):``            ``ans ``=` `ans ``+` `1``    ``return` `ans` `Output ``=` `FindLeapYear(``Input``)` `# Printing``print``(``"No of leap years are:"``, Output)`

Output:

`No of leap years are: 2`

Time Complexity: O(n) where n is the size of the list.

Auxiliary Space: O(1)

Method #3:Using a list comprehension

This method involves using a list comprehension to create a list of all the leap years in the input list, and then finding the length of that list. Here’s an example of how it could be done:

## Python3

 `# Input list initialization``Input` `=` `[``2001``, ``2002``, ``2003``, ``2004``, ``2005``, ``2006``,``         ``2007``, ``2008``, ``2009``, ``2010``, ``2011``, ``2012``]` `# Find leap years``leap_years ``=` `[year ``for` `year ``in` `Input` `if` `year ``%` `4` `=``=` `0` `and` `(year ``%` `100` `!``=` `0` `or` `year ``%` `400` `=``=` `0``)]` `# Find number of leap years``Answer ``=` `len``(leap_years)` `print``(``"No of leap years are:"``, Answer)``#This code is contributed by Edula Vinay Kumar Reddy`

Output

`No of leap years are: 3`

Time Complexity: O(n) where n is the size of the list.

Auxiliary Space: O(1)

My Personal Notes arrow_drop_up