In Python use a for loop and swap the first and last items, the second and the one before the last item, and so on until the given list is reversed.
Example reverse a list in Python without reverse function
Simple example code.
list1 = [1, 2, 3, 4, 5] L = len(list1) for i in range(int(L / 2)): n = list1[i] list1[i] = list1[L - i - 1] list1[L - i - 1] = n print(list1)
list1 = [1, 2, 3, 4, 5] def reverse_fun(numbers): if len(numbers) == 1: return numbers # Otherwise return reverse_fun(numbers[1:]) + numbers[0:1] print(reverse_fun(list1))
list1 = ['A', 'B', 'C', 'D'] def reverse(data_list): return data_list[::-1] print(reverse(list1))
Output: [‘D’, ‘C’, ‘B’, ‘A’]
Create a reverse method for a python list from scratch
def reverse_fun(data_list): length = len(data_list) s = length new_list = [None] * length for item in data_list: s = s - 1 new_list[s] = item return new_list list1 = [1, 2, 3, 4, 5] print(reverse_fun(list1))
Output: [5, 4, 3, 2, 1]
Do comment if you have questions and suggestions on this Python list tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.