11.4k views
4 votes
Write a function named reverse_list that takes as a parameter a list and and reverses the order of the elements in that list. It should not return anything - it should mutate the original list. This can be done trivially using slices, but your function must not use any slicing.

User Nihulus
by
4.6k points

1 Answer

3 votes

Answer:

The function in python is as follows:

def reverse_list(nums):

half =int(len(nums)/2)

for i in range(half):

nums[i], nums[len(nums)-i-1] = nums[len(nums)-i-1],nums[i]

print(nums)

Step-by-step explanation:

This defines the function

def reverse_list(nums):

This gets the half the length of the list

half =int(len(nums)/2)

This iterates through the list

for i in range(half):

This swaps list items with the opposite item on the other half

nums[i], nums[len(nums)-i-1] = nums[len(nums)-i-1],nums[i]

This prints the new list

print(nums)

User Ricardo Costa
by
4.9k points