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

Python Reverse a List

Python Reverse a List

Document Object Reference Manual Python3 Examples

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

(

)

print

(

my_list

)

Code analysis:

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

]

print

(

reversed_list

)

Code analysis:

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

)

)

print

(

reversed_list

)

Code analysis:

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

]

)

print

(

reversed_list

)

Code analysis:

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.

Document Object Reference Manual Python3 Examples