Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Reverse the Elements of a List

Python Reverse the Elements of a List

Document Object Reference Manual Python3 Examples

In Python, there are several ways to reverse the elements of a list. The most common are using the list's reverse() method or using the slice operation [::-1]. Below we show both methods.

Example

Method 1: use the reverse() method

my_list

=

[

1

,

2

,

3

,

4

,

5

]

my_list.

reverse

(

)

print

(

"Using the reverse() method:"

,

my_list

)

Method 2: use a slice operation

my_list

=

[

1

,

2

,

3

,

4

,

5

]

reversed_list

=

my_list

[

::-

1

]

print

(

"Using a slice operation:"

,

reversed_list

)

Code analysis:

  1. Method 1: use reverse() Method

  2. my_list.reverse():reverse() is a built-in list method that modifies the original list in place, reversing the order of its elements. It has no return value, so it operates on the original list directly.
  3. print("使用 reverse() 方法:", my_list): Print the reversed list.
  4. - `my_list.reverse()`: `reverse()` is a built-in list method that modifies the original list in place, reversing the order of its elements. It has no return value, so it operates on the original list directly. - `print("Using the reverse() method:", my_list)`: print the reversed list.
    1. Method 2: use a slice operation

    2. my_list[::-1]: The slice operation [::-1] creates a new list containing the elements of the original list in reverse order.[::-1] means starting from the end of the list with a step of -1, that is, traversing the list backwards.
    3. print("使用切片操作:", reversed_list): Print the new list obtained by the slice operation.
    4. - `my_list[::-1]`: the slice operation `[::-1]` creates a new list containing the elements of the original list in reverse order. `[::-1]` means starting from the end of the list with a step of -1, that is, traversing the list backwards. - `print("Using a slice operation:", reversed_list)`: print the new list obtained by the slice operation.

      Output result:

      使用 reverse() 方法: [5, 4, 3, 2, 1]
      使用切片操作: [5, 4, 3, 2, 1]
      

      Both methods can reverse the elements of a list; which one you choose depends on whether you need to keep the original list. If you want to modify the original list directly, you can use the reverse() method; if you want to keep the original list and create a new reversed list, you can use a slice operation.

      Document Object Reference Manual Python3 Examples