code: def nsmallest(n, iterable, key=None):
      if n == 1:
          it = iter(iterable)
          sentinel = object()
          if key is None:
              result = min(it, default=sentinel)
          else:
              result = min(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)[:n]
      if key is None:
          it = iter(iterable)
          result = [(elem, i) for i, elem in zip(range(n), it)]
          if not result:
              return result
          _heapify_max(result)
          top = result[0][0]
          order = n
          _heapreplace = _heapreplace_max
          for elem in it:
              if elem < top:
                  _heapreplace(result, (elem, order))
                  top = result[0][0]
                  order += 1
          result.sort()
          return [r[0] for r in result]
      it = iter(iterable)
      result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
      if not result:
          return result
      _heapify_max(result)
      top = result[0][0]
      order = n
      _heapreplace = _heapreplace_max
      for elem in it:
          k = key(elem)
          if k < top:
              _heapreplace(result, (k, order, elem))
              top = result[0][0]
              order += 1
      result.sort()
      return [r[2] for r in result]