0
Difference between 'for i in list'and 'for i in range'
Can you please help me with an example in python for the usage of following 2 loops: list=[1,2,3,4] 1. for i in list: 2. for i in range (len(list)): Please give suitable examples for the above cases
8 Answers
+ 7
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)
+ 2
In the first code you are changing the list directly
In the second, i is a copy of the values of the list that's why the list don't change
+ 1
list = [4,5,2,1]
for i in list:
i takes each value of the list
First loop i=4
Second loop i=5
#len(list) = 4
for i in range(len(list)):
i takes the values from 0 to 3
First loop i=0
Second loop i=1
+ 1
Alejandro Medero 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']
+ 1
Gowtham Subramaniyan
nums = [1, 2, 3]
for i in nums:
nums[nums.index(i)] = 1
print(nums)
// [1, 1, 1]
*It's just a hack.* You should just iterate over keys of the list if you want to mutate the list
+ 1
Gowtham Subramaniyan this code change the values of the list
for i in range(len(nums)):
nums[i] ='hello'
0
David Ashton Alejandro Medero Thank you. But how do I change value of the items in the list to 'hello' instead of just creating a copy or temporary list.
0
Roneel Thanks bro. I can understand that it is a hack, but isn't there a standard syntax for doing what I wished to do with the list..?