lst = [(8, 7), (9, 6), (4, 8), (3, 5), (9, 4)]
for i in range(len(lst)):
lst[i] = list(lst[i])
this is working fine.
for i in lst:
i = list(i)
but this is not working. I don't know why ? Can anyone please tell me the reason ?
CodePudding user response:
The docs for Mutable Sequence Types such as list explain assignment of an object x to an item at index i within a sequence s as follows:
Operation:
s[i] = xResult: item
iofsis replaced byx
This means that the line in your code reading lst[i] = list(lst[i]) will replace item i of lst with list(lst[i])), which is a newly created list containing the elements of the tuple referenced by lst[i].
In contrast, consider your code reading:
for i in lst:
i = list(i)
The for statement assigns the item at index 0 of lst to the variable i and executes the statement i = list(i), then on its next iteration assigns the item at index 1 of lst to i and again executes the statement i = list(i), and so forth until lst has been exhausted.
Note that:
the assignment to the variable
iby the for loop causesito be a reference to an item inlstbecause every item in
lstis originally atuple, and becausetupleis animmutable sequence type, there is no way to change the object referenced byiand hence no way to changelstusingi- Interesting side note: If
lstwere a list of lists (instead of a list of tuples), then we would be able to modify an item oflstusingi, for example as follows:
lst = [[8, 7], [9, 6], [4, 8], [3, 5], [9, 4]] for i in lst: i[:] = i [0] i.append(1) print(lst) # Output: [[8, 7, 0, 1], [9, 6, 0, 1], [4, 8, 0, 1], [3, 5, 0, 1], [9, 4, 0, 1]]- Interesting side note: If
list(i)creates a new object of typelistfrom the tupleii = list(i)assigns that new object to the variablei, so thatiis now a reference to the newly createdlistobject; the object thatipreviously referenced, namely thetupleitem inlst, remains intact as an item oflst.
CodePudding user response:
In the second option you just assign list(i) to the name i, then do nothing with it until it is overwritten in the next loop.
An alternative:
lst[:] = list(map(list, lst))
print(lst)
output: [[8, 7], [9, 6], [4, 8], [3, 5], [9, 4]]
CodePudding user response:
In your first code
for i in range(len(lst)):
lst[i] = list(lst[i])
lst[i] is a variable which directly point to the element in list. Hence, any change in it effects the list itself.
Whereas in your second code
for i in lst:
i = list(i)
i is a variable used in for loop and is not pointing to the list lst. Hence, any change to id doesn't affect the lst.
CodePudding user response:
What you are doing in the first code is,lst[i] = list(lst[i]) putting the value of the converted list in the index of the list whereas in your second code you are just assigning that converted list to i
you can try this:
lst = [(8, 7), (9, 6), (4, 8), (3, 5), (9, 4)]
lst = [list(i) for i in lst]
