Python Tutorial (33) – Example: Reversing a list

Time: Column:Python views:309

Define a List and Reverse It

This Python code demonstrates how to define a list and reverse its elements using different methods.

Example:

Before reversing:

list = [10, 11, 12, 13, 14, 15]

After reversing:

[15, 14, 13, 12, 11, 10]

Example 1: Using reversed()

def Reverse(lst):
    # Use list comprehension with reversed() to reverse the list
    return [ele for ele in reversed(lst)]

# Define the list
lst = [10, 11, 12, 13, 14, 15]

# Call the function and print the result
print(Reverse(lst))

Output:

[15, 14, 13, 12, 11, 10]

Example 2: Using reverse() Method

def Reverse(lst):
    # Use the reverse() method to reverse the list in place
    lst.reverse()
    return lst

# Define the list
lst = [10, 11, 12, 13, 14, 15]

# Call the function and print the result
print(Reverse(lst))

Output:

[15, 14, 13, 12, 11, 10]

Example 3: Using Slicing

def Reverse(lst):
    # Use list slicing to reverse the list
    new_lst = lst[::-1]
    return new_lst

# Define the list
lst = [10, 11, 12, 13, 14, 15]

# Call the function and print the result
print(Reverse(lst))

Output:

[15, 14, 13, 12, 11, 10]

Explanation:

  1. Example 1 uses the reversed() function along with list comprehension to create a new reversed list.

  2. Example 2 reverses the list in place using the reverse() method, which modifies the original list.

  3. Example 3 demonstrates using Python list slicing [::-1] to reverse the list, returning a new reversed list.

All three methods effectively reverse the elements of the list.