[Solved] Reverse first n items of the list and return it


>>> def reverse(n, lst):
        if n <= 0:
            return []
        return lst[:n][::-1] + lst[n:]

>>> reverse(4, ['f', 'o', 'o', 't', 'b', 'a', 'l', 'l'])
['t', 'o', 'o', 'f', 'b', 'a', 'l', 'l']
>>> 

Explanation:

  • if n <= 0:: if n is less than or equal to zero…
  • return []: return an empty list. Otherwise…
  • return lst[:n][::-1]: return all the elements in the range n and reverse them. Plus…
  • lst[n:]: The rest of the elements past range n.

solved Reverse first n items of the list and return it