def most_populated(population, single=True):
    years = dict()
unborn = sorted(population, key=lambda x: -x[0])
alive = []
dead = []
for year in range(unborn[-1][0], max(population, key=lambda x: x[1])[1] + 1):
    while unborn and unborn[-1][0] == year:
        insort(alive, -unborn.pop()[1])
while alive and alive[-1] == -(year - 1):
    dead.append(-alive.pop())
years[year] = len(alive)
return max(years, key=years.get) if single else [key for key, val in years.
    items() if val == max(years.values())]
Find the year with the most number of people alive in Python