# [REPORTED] 2. CS102: Data Structures and Algorithms / linked-lists / swapping-elements-in-a-linked-list-python

``````import Node

def swap_nodes(input_list, val1, val2):
print(f'Swapping {val1} with {val2}')

node1_prev = None
node2_prev = None

if val1 == val2:
print("Elements are the same - no swap needed")
return

while node1 is not None:
if node1.get_value() == val1:
break
node1_prev = node1
node1 = node1.get_next_node()

while node2 is not None:
if node2.get_value() == val2:
break
node2_prev = node2
node2 = node2.get_next_node()

if (node1 is None or node2 is None):
print("Swap not possible - one or more element is not in the list")
return

if node1_prev is None:
else:
node1_prev.set_next_node(node2)

if node2_prev is None:
else:
node2_prev.set_next_node(node1)

temp = node1.get_next_node()
node1.set_next_node(node2.get_next_node())
node2.set_next_node(temp)

for i in range(10):
ll.insert_beginning(i)

print(ll.stringify_list())
swap_nodes(ll, 9, 5)
print(ll.stringify_list())
``````
``````9
8
7
6
5
4
3
2
1
0

Swapping 9 with 5
Traceback (most recent call last):
File "script.py", line 52, in <module>
swap_nodes(ll, 9, 5)
File "script.py", line 33, in swap_nodes
NameError: name 'self' is not defined
``````
1 Like

This isn’t a bug. In line 33, you use `self`. However, you did not include self as a parameter in your function declaration. Therefore, Python does not know that this is an instance method. You can’t access `self` in a regular function, you need to use it in an instance method (otherwise, how does the computer know what object you’re referring to?).

1 Like

This is example code, I didn’t write it. I just noticed the self, and changed the function call to invoke the faulty code.

1 Like

Ah ok, I missed that, sorry. I’ve submitted a bug report, hopefully it’ll be fixed soon, thanks!

2 Likes