Python Reverse a List
In Python, a list can be reversed in several ways. Here are some common methods:
Method 1: use reverse() Method
reverse() The method modifies the original list directly, reversing the order of its elements.
Example
my_list
=
[
1
,
2
,
3
,
4
,
5
]
my_list.
reverse
(
)
(
my_list
)
Code analysis:
my_list.reverse(): Callingreverse()The method reverses the order of the elements of the listmy_list.print(my_list): Print the reversed list.
Output result:
[5, 4, 3, 2, 1]
Method 2: use a slice operation
The slice 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
]
(
reversed_list
)
Code analysis:
my_list[::-1]: Use a slice operation to traverse the list from the last element with a step of -1, producing a new reversed list.print(reversed_list): Print the reversed list.
Output result:
[5, 4, 3, 2, 1]
Method 3: use reversed() function
reversed() The function returns a reversed iterator, which can be converted to a list with the list() function.
Example
my_list
=
[
1
,
2
,
3
,
4
,
5
]
reversed_list
=
list
(
reversed
(
my_list
)
)
(
reversed_list
)
Code analysis:
reversed(my_list): Returns a reversed iterator.list(reversed(my_list)): Convert the iterator to a list.print(reversed_list): Print the reversed list.
Output result:
[5, 4, 3, 2, 1]
Method 4: reverse manually with a loop
You can also reverse a list manually with 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
]
)
(
reversed_list
)
Code analysis:
for i in range(len(my_list) - 1, -1, -1): Start from the last index of the list and iterate backwards to the first index.reversed_list.append(my_list[i]): Add each element visited toreversed_listit.print(reversed_list): Print 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 preference.
Python3 Examples