The SageMath has a great S-Box package that is heavily used by S-Box designers. If you are going to learn/play with S-Boxes you may benefit from this package.
With Sbox Package (Try online)
from sage.crypto.sbox import SBox
#must be power of two otherwise error
p = Permutations(range(16)).random_element()
S = SBox(p);
print("The permutation ", S)
print("The inverse permutation", S.inverse())
SageMath currently using Python3, so one can write their version very easily either in Python or SageMath (Try online);
P = Permutations(range(16)).random_element()
print("The permutation ", P)
InverseP=[P.index(i) for i in range(16)]
print("The inverse permutation", InverseP)
As we can see the S-Box package is much better, for example, the construction checks that the size is equal to a power of 2 or not.
Note: I've used random permutations to guarantee that the inverse exists.
As we can see from the Sbox package source
m = self.input_size()
L = [self(i) for i in range(1<<m)]
return SBox([L.index(i) for i in range(1<<m)], big_endian=self._big_endian)
SageMath converts S-Box into a List, takes the inverse on the list then constructs a S-Box on the list. As we can see the inverse - if exist - is not magic.