2

How to reverse a list in python?

 2 years ago
source link: https://dev.to/afizs/how-to-reverse-a-list-in-python-398d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK