Jax Masta Jax Masta - 6 months ago 37
Python Question

Returns a copy of the list with the first number of items reversed

list1 = ['e', 'd', 'u', 'd']
list2 = ['m', 'o', 'b', 'b', 'e', 'd']

def reverse(list, number):
number = (my_list[0])
for i in my_list:
my_list = str(my_list[number]) + str(i)
return my_list


OutPut should be:
[d,u,d,e]
[b,o,m,b,e,d]

Answer
>>> list1 = ['e', 'd', 'u', 'd']
>>> list2 = ['m', 'o', 'b', 'b', 'e', 'd']
>>> def reverse(L, num):
...     return L[:num][::-1] + L[num:]
... 
>>> reverse(list1, 4)
['d', 'u', 'd', 'e']
>>> reverse(list2, 3)
['b', 'o', 'm', 'b', 'e', 'd']

Using only loops:

>>> list1 = ['e', 'd', 'u', 'd']
>>> list2 = ['m', 'o', 'b', 'b', 'e', 'd']
>>> def reverse(L, num):
...     new_list=[]
...     for i in reversed(range(num)):
...          new_list+=L[i]
...     for i in range(num, len(L)):
...          new_list+=L[i]
...     return new_list
... 
>>> reverse(list1, 4)
['d', 'u', 'd', 'e']
>>> reverse(list2, 3)
['b', 'o', 'm', 'b', 'e', 'd']
Comments