Reputation: 43
I am writing a series of python methods with different sorts. What I have is user inputted numbers which I turn into a list. I then run my bubble_sort method on the input list and I then print the result. I have my initial input list saved so that I can re-sort using selection_sort but when I print out my original list I instead am printing the bubble_sorted list. I am new to python so I am not sure if I am missing a fundamental concept about variables in the language. Here is my code
def listify(i):
temp_list = []
input_list_local = []
input_list_local = list(i)
for char in input_list_local:
if char.isdigit():
temp_list.append(char)
return temp_list
def bubble_sort(input):
for i in range(len(input)-1):
for j in range(len(input)-1):
if(input[j] > input[j+1]):
tmp = input[j]
input[j] = input[j+1]
input[j+1] = tmp
return input
def selection_sort(input):
pass
input = raw_input("enter random numbers here seperated by spaces-> ")
print("you entered "+input)
input_list = listify(input)
print(input_list)
pass_list = input_list
print(bubble_sort(pass_list))
print(input_list) #should print original input list. Instead prints sorted list
Upvotes: 2
Views: 44
Reputation: 122446
You are modifying the same list: pass_list = input_list
means that pass_list
is just a different name for the same list object. So after calling bubble_sort(pass_list)
you've modified pass_list
but also input_list
because they're the same object (in memory). Hence you're seeing the sorted list when you're printing input_list
.
You can fix it by doing:
pass_list = input_list[:]
This makes a copy of input_list
by using Python's slicing notation. You can then safely sort pass_list
and it won't affect the original input_list
.
Upvotes: 4