Published in

CodeX

Reversing Different Objects in Different Ways in Python

Hello, We are going to explore various ways of reversing objects (string, list, …) in python.

Reversing a list with reverse() method

This method does not take any arguments and return anything. It just reverses the original list.

Reversing a list with reversed() function

It returns an iterator object so that we can iterate over the list in reverse order. It does not change the original list.

We can use either list comprehension (in the image) or list() function to create the reversed of the original list as a new list.

With list() function which uses iteration but internally, we should write x=list(r). We should pay attention that if we apply one of these two ways on r again, we get an empty list.

This is because r is an iterator so when doing above statements python internally behind the scene uses next(r) in each iteration to access values inside r. the following code makes my point.

With iter() function we can create an iterator from a list.

Reversing a list with reversed subsetting

This returns a copy of the list.

Reversing a list with NumPy library

NumPy is a python library for linear algebra. We can use it’s flip() method to reverse a list (array) created with NumPy. It returns a new array.

Reversing matrices along chosen axis with NumPy library

I demonstrate this on a 2D matrix. the flip() method about which I talked earlier has a second optional argument that can be None or integer or tuple of integers. use that to flip along desired axis or axes.

The default, axis=None, will flip over all of the axes of the input array. If axis is a tuple of integers, flipping is performed on all of the axes specified in the tuple.

If you are confused about it, along axis 0 means in vertical direction along the rows and considering the items of the most outer level of brackets. Along the axis 1 means in horizontal direction along the columns and considering the items of the second most outer level of brackets.

Please refer to this link at the documentation for a 3D example:

https://numpy.org/doc/stable/reference/generated/numpy.flip.html

Reversing an integer

In this example if you follow each iteration of the loop you see that the process inside the loop is easy. (pen and paper can help)

Reversing each key-value pair in a dictionary

Thanks for reading. wish you peace. if you liked it please press clap option.

--

--

--

Sepehr

I write on topics that help us have a better life both financially (DeFi, business,…) and mentally (art, philosophy,…)