code: def nlargest(n, iterable, key=None):
      if n == 1:
          it = iter(iterable)
          sentinel = object()
          if key is None:
              result = max(it, default=sentinel)
          else:
              result = max(it, default=sentinel, key=key)
          return [] if result is sentinel else [result]
      try:
          size = len(iterable)
      except (TypeError, AttributeError):
          pass
      else:
          if n >= size:
              return sorted(iterable, key=key, reverse=True)[:n]
      if key is None:
          it = iter(iterable)
          result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)]
          if not result:
              return result
          heapify(result)
          top = result[0][0]
          order = -n
          _heapreplace = heapreplace
          for elem in it:
              if top < elem:
                  _heapreplace(result, (elem, order))
                  top = result[0][0]
                  order -= 1
          result.sort(reverse=True)
          return [r[0] for r in result]
      it = iter(iterable)
      result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
      if not result:
          return result
      heapify(result)
      top = result[0][0]
      order = -n
      _heapreplace = heapreplace
      for elem in it:
          k = key(elem)
          if top < k:
              _heapreplace(result, (k, order, elem))
              top = result[0][0]
              order -= 1
      result.sort(reverse=True)
      return [r[2] for r in result]