DEV Community

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

Posted on

2

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.

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay