1

I defined a function, which could swap the elements in the string. When I used the swapx function twice, there is an error. Here is my code.

def swapx(lst):
    helper=lst[0]
    lst[0]=lst[-1]
    lst[-1]=helper

s=list("python")
swapx(s)
print(s)
swapx(swapx(s))

['n', 'y', 't', 'h', 'o', 'p']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-100-f89e12aa1f31> in <module>
      7 swapx(s)
      8 print(s)
----> 9 swapx(swapx(s))

<ipython-input-100-f89e12aa1f31> in swapx(lst)
      1 def swapx(lst):
----> 2     helper=lst[0]
      3     lst[0]=lst[-1]
      4     lst[-1]=helper
      5 

TypeError: 'NoneType' object is not subscriptable

2 Answers2

3

Your function is not returning anything, so by doing

swapx(swapx(s))

you are trying to apply your function to None, and not to a list. Try this:

def swapx(lst):
    helper=lst[0]
    lst[0]=lst[-1]
    lst[-1]=helper
    return lst

s = list("python")
print(swapx(s))
swapx(s)
print(swapx(swapx(s)))

result will be:

['n', 'y', 't', 'h', 'o', 'p']
['p', 'y', 't', 'h', 'o', 'n']

if you run

s = list("python")
print(swapx(swapx(s)))

result will be

['p', 'y', 't', 'h', 'o', 'n']

so you will get the same list, as the function is applied twice...but it works, you will not get an error

As @LiMar suggested, you can write a more pythonic swap:

def swapx(lst):
    lst[0], lst[-1] = lst[-1], lst[0]
    return lst
Deffo
  • 191
  • 1
  • 8
  • 21
  • 4
    That is not quite correct. A function without a return statement explicitly returns "None". Not a function object. Hence the error message "'NoneType' object is not subscriptable" it means that you can't use the []-operator on None Type – A.Franzen Jun 21 '21 at 09:30
  • 1
    @A.Franzen you're right! Sorry for the mistake, I'll correct my answer – Deffo Jun 21 '21 at 09:31
  • 4
    Swap operation can be done without helper `lst[0],lst[-1] = lst[-1], lst[0]` – LiMar Jun 21 '21 at 09:31
0

It works for me if you do it like this:

def swapx(lst):
    helper=lst[0]
    lst[0]=lst[-1]
    lst[-1]=helper
    return lst

s=list("python")
s = swapx(s)
print(s)
swapx(s)
print(s)
swapx(s)
print(s)
Joshua
  • 551
  • 4
  • 13