>>> 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:
: ifn
is less than or equal to zero…return []
: return an empty list. Otherwise…return lst[:n][::-1]
: return all the elements in the rangen
and reverse them. Plus…lst[n:]
: The rest of the elements past rangen
.
solved Reverse first n items of the list and return it