I have a list of lists:
LofL = [["string", "number", "number", "number"], ["string", "number", "number", "number"], ...]
and im trying to turn the numbers within the list of lists to floats instead of strings. Each list of list is not equal in length. So far I have:
for sublist in LofL:
sublist[1:] = float(sublist[1:])
but I’m getting the error float argument must be a string or real number not a list. This works for single numbers if I do sublist[1] = float(sublist[1]) but I’m unsure of how to include all numbers in each list of lists without the [1:] indexing.
>Solution :
for sublist in LofL:
for i in range(1, len(sublist)):
sublist[i]=float(sublist[i])
Explanation:
Your initial code sublist[1:]=float(sublist[1:] will not work as sublist[1:] is a list and you cannot turn list to a float.
So the for i in range(1, len(sublist) will iterate through each element in your sublist
then with each iteration we will convert sublist[i]=float(sublist[i] into float. Because you specified that the first item of sublist does not need to change hence we are starting our loop from 1