+ 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']

21st Jun 2020, 4:57 PM
Gowtham Subramaniyan
Gowtham Subramaniyan - avatar
5 Respuestas
+ 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.
21st Jun 2020, 5:06 PM
XXX
XXX - avatar
+ 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)
22nd Jun 2020, 4:07 AM
David Ashton
David Ashton - avatar
+ 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
21st Jun 2020, 10:59 PM
Bilbo Baggins
Bilbo Baggins - avatar
+ 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.
22nd Jun 2020, 5:37 AM
Gowtham Subramaniyan
Gowtham Subramaniyan - avatar
+ 1
just reassign the temporary list ;) nums = ['hello' for i in nums] print(nums)
22nd Jun 2020, 1:58 PM
Bilbo Baggins
Bilbo Baggins - avatar