Python Reverse List

Document 对象参考手册Python3 Examples

In Python, a list can be reversed in many ways. Here are several common methods:

Method 1: Usingreverse()Method

reverse()The method directly modifies the original list, reversing the order of its elements.

Example

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)

Code Analysis:

  • my_list.reverse(): Call thereverse()method to reverse the listmy_list's element order.
  • print(my_list): Output the reversed list.

Output result:

[5, 4, 3, 2, 1]

Method 2: Using Slicing

The slicing operation[::-1]can create a new reversed list without modifying the original list.

Example

my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)

Code Analysis:

  • my_list[::-1]: Use slicing to traverse the list starting from the last element with a step of -1, generating a new reversed list.
  • print(reversed_list): Output the reversed list.

Output result:

[5, 4, 3, 2, 1]

Method 3: Usingreversed()Function

reversed()The function returns a reversed iterator, which can be converted into a list using thelist()function.

Example

my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)

Code Analysis:

  • reversed(my_list): Returns a reversed iterator.
  • list(reversed(my_list)): Converts the iterator into a list.
  • print(reversed_list): Output the reversed list.

Output result:

[5, 4, 3, 2, 1]

Method 4: Manually Reversing Using a Loop

You can also manually reverse a list using a loop.

Example

my_list = [1, 2, 3, 4, 5]
reversed_list = []
for i in range(len(my_list) - 1, -1, -1):
    reversed_list.append(my_list[i])
print(reversed_list)

Code Analysis:

  • for i in range(len(my_list) - 1, -1, -1): Starting from the last index of the list, traverse backward to the first index.
  • reversed_list.append(my_list[i]): Add the traversed elements toreversed_list.
  • print(reversed_list): Output the reversed list.

Output result:

[5, 4, 3, 2, 1]

All of these methods can reverse a list. Which one you choose depends on your specific needs and preferences.

Document 对象参考手册Python3 Examples

Other Extensions