Reputation: 407
I have this below function.
def replace_zeros(nums1):
for n in nums1:
print 'nums1=', nums1, 'n=', n
if n == 0:
nums1[nums1.index(n)] = 2
return nums1
print replace_zeros([1,2,3,0,0,0])
which was giving me the following output
>>> print replace_zeros([1,2,3,0,0,0])
nums1= [1, 2, 3, 0, 0, 0] n= 1
nums1= [1, 2, 3, 0, 0, 0] n= 2
nums1= [1, 2, 3, 0, 0, 0] n= 3
nums1= [1, 2, 3, 0, 0, 0] n= 0
nums1= [1, 2, 3, 2, 0, 0] n= 0
nums1= [1, 2, 3, 2, 2, 0] n= 0
I am getting 'n' from nums1 only but why 'n' value is not changing even 'nums1' is changed? Could you let know how to change 'nums1' with changing value?
Consider this below python function
def replace_zeros(nums1):
for n in nums1:
nums1.insert(1, 2)
nums1 = nums1[:-1]
print 'nums1=', nums1, 'n=', n
if n == 0:
nums1[nums1.index(n)] = 2
return nums1
print replace_zeros([1,2,3,0,0,0])
I am getting index error at "nums1[nums1.index(n)] = 2", why still I am getting index error even if I check n==0? i.e.even though nums1 is changing inside loop, the 'n' value that we first retrieved from 'for' loop did not change. I want that 'n' to be changed along with nums1.
I am looking for something like reloading nums1 so that 'n' will change and 'n==0' condition should become False to do not enter that 'if' block so that no index error raises.
I know that what 'n' should contain will be defined when we do 'for n in nums1', but I want that 'n' to be dynamically changed with changing 'nums1' inside for loop.
Upvotes: 0
Views: 220
Reputation: 3483
If you don't need the print statements, I recommend a list comprehension for the replace function:
def replace_zeros(arr):
return [n if n != 0 else 2 for n in arr]
Upvotes: 1
Reputation: 774
The best method would be to use an enumeration:
def replace_zeros(nums1):
for index,n in enumerate(nums1):
if n == 0:
nums1[index] = 2
print('nums1=', nums1, 'n=', n)
return nums1
Upvotes: 0
Reputation: 1413
Because you are replacing 0
with 2
but you are not changing the value of n
inside if
statement where you are replacing zeros
def replace_zeros(nums1):
for n in nums1:
if n == 0:
nums1[nums1.index(n)] = 2
n = 2
print('nums1=', nums1, 'n=', n)
return nums1
print(replace_zeros([1,2,3,0,0,0]))
Output:
nums1= [1, 2, 3, 0, 0, 0] n= 1
nums1= [1, 2, 3, 0, 0, 0] n= 2
nums1= [1, 2, 3, 0, 0, 0] n= 3
nums1= [1, 2, 3, 2, 0, 0] n= 2
nums1= [1, 2, 3, 2, 2, 0] n= 2
nums1= [1, 2, 3, 2, 2, 2] n= 2
[1, 2, 3, 2, 2, 2]
Upvotes: 0