Binyamin Even
Binyamin Even

Reputation: 3382

Converting list with 1 variable to float in Python

I have a list variable with one element,

x=['2']

and I want to convert it to a float:

x=2.0 

I tried float(x), or int(x) - without success.

Can anyone please help me?

Upvotes: 1

Views: 560

Answers (1)

Jamie Bull
Jamie Bull

Reputation: 13519

You need to convert the first item in your one-item list to a float. The approaches you tried already are trying to convert the whole list to a float (or an int - not sure where you were going with that!).

Python is zero-indexed (index numbers start from zero) which means that the first item in your list is referred to as x[0].

So the snippet you need is:

x = float(x[0])

Upvotes: 1

Related Questions