def make_to_str_list(list):
for c in range(0, len(list)):
list[c] = str(list[c])
return list
def count_zeros(list):
i = 0 # setting up the counter
list = make_to_str_list(list) # changes the list from a list of integers to a list of strings
print(list)
string = ''.join(list) # changes list to a string
print(string)
while string.find('0') != -1: # this is checking if there is a '0' in the string
del list[string.find('0')] # this deletes the '0' from the string
string = ''.join(list) # this updates the string for the while loop
print(string)
i += 1 # adds a count
return i # returns the count
x = [1, 2, 0, 4, 0, 6, 7, 8, 9]
print(x)
print(count_zeros(x))
print(x)
Hello, I am rather new to python, and I have been experimenting with functions.
The make_to_str_list
function takes a list of numbers and replaces it with a string version of the number for use in the count_zeros
function. I've had no issues with the make_to_str_list
function. The problem I am having is that when I pass the list x
into the count_zeros
function, the function alters the list for the remainder of the code. The issue seems to lie with the while loop, as I can remove the loop and it no longer alters x
for the entirety of the code. I have also noted that if I indent return i
into the while loop, it also prevents the list x
from being altered for the remainder of the code. However, I am assuming that is because it is prematurely stopping the function during the while loop, as the function returns a 1
instead of the 2
I am expecting. Here is what is printed from the code: [1, 2, 0, 4, 0, 6, 7, 8, 9]
['1', '2', '0', '4', '0', '6', '7', '8', '9']
120406789
12406789
1246789
2
['1', '2', '4', '6', '7', '8', '9']
The first print is from before the function to make sure that x = [1, 2, 0, 4, 0, 6, 7, 8, 9]
The next four prints are from within the function. The print 2
is the returned value from the function, and the print ['1', '2', '4', '6', '7', '8', '9']
is the altered x
list after the function has been called.