Function that changes the original list and doesn't return anything
Question:
I need to define a function that looks at the list and moves the zeros to the end of the list. It has to do it in place and not return anything. It just needs to modify the original list. I can get it to work only if I am returning a value which is wrong of course. How far away am I?
def move_zero(lst):
a = lst
zero = []
rest = []
for num in a:
if num == 0:
zero.append(num)
else:
rest.append(num)
a = rest + zero
return a
lst = a
print(move_zero([0,1,0,2,0,3,0,4]))
They give me hints. Though no matter how much I go back and re-watch the course material I don’t seem to understand how it helps. Hint #1:
for i in range(start = length of non_zero_lst , end = length of the whole list (lst) :
lst[i] = 0
Hint #2:
lst[i], lst[count] = lst[count], lst[i]
Answers:
All this business with creating and manipulating copies of the list is unnecessary, you can directly work on the original list itself. My suggestion to do that would be the following:
my_list = [1, 5, 0, 9, 5, 0, 7]
def my_fun():
global my_list
for item in my_list:
if item == 0:
my_list.remove(item)
my_list.append(item)
return
my_fun()
print(my_list)
Alternatively, it also works by passing the list by reference as an argument to the function:
my_list = [1, 5, 0, 9, 5, 0, 7]
def my_fun(lst):
for item in lst:
if item == 0:
lst.remove(item)
lst.append(item)
return
my_fun(my_list)
print(my_list)
I need to define a function that looks at the list and moves the zeros to the end of the list. It has to do it in place and not return anything. It just needs to modify the original list. I can get it to work only if I am returning a value which is wrong of course. How far away am I?
def move_zero(lst):
a = lst
zero = []
rest = []
for num in a:
if num == 0:
zero.append(num)
else:
rest.append(num)
a = rest + zero
return a
lst = a
print(move_zero([0,1,0,2,0,3,0,4]))
They give me hints. Though no matter how much I go back and re-watch the course material I don’t seem to understand how it helps. Hint #1:
for i in range(start = length of non_zero_lst , end = length of the whole list (lst) :
lst[i] = 0
Hint #2:
lst[i], lst[count] = lst[count], lst[i]
All this business with creating and manipulating copies of the list is unnecessary, you can directly work on the original list itself. My suggestion to do that would be the following:
my_list = [1, 5, 0, 9, 5, 0, 7]
def my_fun():
global my_list
for item in my_list:
if item == 0:
my_list.remove(item)
my_list.append(item)
return
my_fun()
print(my_list)
Alternatively, it also works by passing the list by reference as an argument to the function:
my_list = [1, 5, 0, 9, 5, 0, 7]
def my_fun(lst):
for item in lst:
if item == 0:
lst.remove(item)
lst.append(item)
return
my_fun(my_list)
print(my_list)