I am trying to convert all the element of given list into float. But the output is surprising me. I am iterating through the elements using 2 for loop and converting every element to float and adding converted element to another list "c". once the inner loop finished I append the list c into b and clear the list c for next iteration. While clearing "c" the content of b also got removed and updated with next iteration elements. And finally the b is again appended with current list of c. So b is updated as last iteration elements present in c.
I thought the list.clear() is referencing the object when we assign it to another variable. So if we are doing something on it, it will also affect the referenced variable (like clear c is affecting b). However, This can be rectified if we reinitialize c i.e c=[]. Other simple logics like using range will give better results. But, I would like to get proper explanations for this clear() method.
a=[['4','5',6],['1','2','3']]
b=[]
c=[]
for i in a:
c.clear()
# c=[]
for j in i:
c.append(float(j))
b.append(c)
print(b)
CodePudding user response:
The straight forward answer to your solution is to add .copy()
in the line b.append(c.copy())
. So it will look like
a = [['4', '5', 6], ['1', '2', '3']]
b = []
c = []
for i in a:
c.clear()
# c=[]
for j in i:
c.append(float(j))
b.append(c.copy())
print(b)
However this solution is rather slow as it consumes O(n^2) time. If you just want a single list of float at the end then you can use itertools for example.
import itertools
a = [['4', '5', 6], ['1', '2', '3']]
b=[]
for item in itertools.chain.from_iterable(a):
b.append(float(item))
print(b)
There are more simple solutions instead of using two nested loops. Add a comment if you need more suggestion. I mentioned itertools because in order to introduce you to it as it comes very handy. This problem can be solved without itertools too.
CodePudding user response:
probably, you want to do:
a=[['4','5',6],['1','2','3']]
c = [float(x) for x in sum(a,[])]
if you want to follow your way then:
a=[['4','5',6],['1','2','3']]
b = [[float(x) for x in i] for i in a]
you don't need c.