0

i have a list of list with:

[['9.2','8.7'],['7.5','6.5']]

and i want to convert them into float values to get:

[[9.2,8.7],[7.5,6.5]]

I've tried this but it doesn't work.

L = [['9.2','8.7'],['7.5','6.5']]
for line in L:
    if line:
        line = [float(i) for i in line]
print(L)

2 Answers 2

3

You can use a nested list comprehension to write:

new_L = [[float(item) for item in line] for line in L]
Sign up to request clarification or add additional context in comments.

Comments

0

You aren't changing the original but creating a new list, so you are not seeing any side effects in L. You can just create a new list with your code:

L = [['9.2','8.7'],['7.5','6.5']]
newL = []
for line in L:
    newL.append([float(i) for i in line])
print(newL)

Alternatively, use a list comprehension:

newL = [[float(n) for n in e] for e in L]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.