How do you reverse a list in Python?
There are 2 good ways to reverse a list.
- Slicing
- 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']
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']
Which method do you prefer? Share your views in the comments.
Top comments (3)
My answer is reversed(iterable).
This don't modify original
Thanks for this! Please keep up with posts like this. Will be very very useful to bookmark.
Thanks for your kind words. Sure I will keep posting the content like this.