Reversing list elements

suggest change

You can use the reversed function which returns an iterator to the reversed list:

In [3]: rev = reversed(numbers)

In [4]: rev
Out[4]: [9, 8, 7, 6, 5, 4, 3, 2, 1]

Note that the list “numbers” remains unchanged by this operation, and remains in the same order it was originally.

To reverse in place, you can also use the reverse method.

You can also reverse a list (actually obtaining a copy, the original list is unaffected) by using the slicing syntax, setting the third argument (the step) as -1:

In [1]: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [2]: numbers[::-1]
Out[2]: [9, 8, 7, 6, 5, 4, 3, 2, 1]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents