+ 1
Why is the second ' for loop' not the changing the items of the list to 'hello' whereas the first one changes as intended?
nums = [1, 2, 3] for i in range (len(nums)): nums[i]='hi' print(nums) for i in nums: i='hello' print(nums) Output: ['hi', 'hi', 'hi'] ['hi', 'hi', 'hi']
5 ответов
+ 5
Because in the first loop, you are using the index to directly change the array. In the second loop, a local variable i is created and you are changing that local variable.
+ 3
In the second loop you are making i be 'hello' for each iteration but you are not putting it back into the list. To see what's going on, insert print() functions into the loop, e.g.
nums = [1, 2, 3]
for i in nums:
print(i)
i='hello'
print(i)
print(nums)
+ 1
for i in nums:
suggest me a list comprehension...
print(['hello' for i in nums])
but in this way a parallel list is generated, the original one is untouched
+ 1
David Ashton Bilbo Baggins XXX Thank you. But how do I put 'hello' in the list in place of the already existing items instead of just creating a copy or temporary list.
+ 1
just reassign the temporary list ;)
nums = ['hello' for i in nums]
print(nums)