Instagram
youtube
Facebook
Twitter

Python Program to Reverse a List in Two Ways

A Python Program to Reverse a List in Two Ways?

Code Explanation:

Method 1 (Slicing):
lst[::-1] uses Python slicing to reverse the list quickly.

Method 2 (Loop):
A loop runs from the end of the list to the start (range(len(lst)-1, -1, -1)) and appends elements to a new list.

Function Definitions:
Two separate functions handle the reversing by slicing and loop method.

Input List:
A sample list [10, 20, 30, 40, 50] is used for testing both methods.

Function Call & Output:
Both functions are called and their reversed outputs are printed.

 

Program:

# Method 1: Using slicing

def reverse_list_slicing(lst):

    return lst[::-1]

# Method 2: Using loop

def reverse_list_loop(lst):

    reversed_list = []

    for i in range(len(lst)-1, -1, -1):

        reversed_list.append(lst[i])

    return reversed_list

# Sample list

my_list = [10, 20, 30, 40, 50]

# Reversing using both methods

print("Reversed using slicing:", reverse_list_slicing(my_list))

print("Reversed using loop:", reverse_list_loop(my_list))