DEV Community

Cover image for How to reverse a list in python?
Afiz
Afiz

Posted on

How to reverse a list in python?

How do you reverse a list in Python?

There are 2 good ways to reverse a list.

  1. Slicing
  2. reverse method

1. Slicing: Generates new list and original list won't be updated.

In [1]: chars = list('abdbbef')

In [2]: chars[::-1]
Out[2]: ['f', 'e', 'b', 'b', 'd', 'b', 'a']
Enter fullscreen mode Exit fullscreen mode

2. Reverse method: reverse method modifies the original list.

In [3]: chars.reverse()

In [4]: chars
Out[4]: ['f', 'e', 'b', 'b', 'd', 'b', 'a']
Enter fullscreen mode Exit fullscreen mode

Which method do you prefer? Share your views in the comments.

Top comments (3)

Collapse
 
sevenc_nanashi profile image
Nanashi. • Edited

My answer is reversed(iterable).
This don't modify original

Collapse
 
sherrydays profile image
Sherry Day

Thanks for this! Please keep up with posts like this. Will be very very useful to bookmark.

Collapse
 
afizs profile image
Afiz

Thanks for your kind words. Sure I will keep posting the content like this.