I am trying to get a output of [3.1]
where the number in the list is a float.
b = "3.1"
list1 = []
for i in b:
list1.append(i)
print(list1)
I expect the output to be [3.1]
, but the code above outputs ['3', '.', '1']
I am trying to get a output of [3.1]
where the number in the list is a float.
b = "3.1"
list1 = []
for i in b:
list1.append(i)
print(list1)
I expect the output to be [3.1]
, but the code above outputs ['3', '.', '1']
for i in b: list1.append(i)
means "for each character in the string b
, append that character to the list list1
", giving you exactly what you asked for: a three-character list.
If you just want to turn b
into float and append to the list, this suffices:
list1.append(float(b))
Try this :
list1 = [float(b)]
OUTPUT :
[3.1]
The reason you're getting a list like ['3', '.', '1']
is because you're iterating over all the characters of string b
. You need to convert the string type of b
to float and then append it to a list.
In the code, variable b is of format string. Convert it to float and append to list.
b = "3.1"
list_1 = []
list_1.append(float(b))
print (list_1)
This should give you the desired output.
The way you are doing, variable b is in string format. This makes the for loop append individual character to list that is respectively '3', '.', '1'. Conversion of string to float should solve your problem.
Let's see what is happening under the hood here
In [9]: b = "3.1"
In [10]: for i in b:
...: print(i)
...:
3
.
1
As you can see, since b
is a string, iterating over a string gives you individual characters of the string, which you end up appending to the list, and the list looks like ['3', '.', '1']
Hence you need to convert the string to a float, and then append it to the list, which is as simple as
In [11]: b = "3.1"
In [12]: [float(b)]
Out[12]: [3.1]
Here we convert b to a float, and create a single list element with 3.1
as it's only element
A similar idea can be applied when you are dealing with a list of strings and each string represents a float, where we convert every element to a float, and make a new list out of it
In [13]: b = [ "2.7", "2.9", "3.1"]
In [14]: [float(i) for i in b]
Out[14]: [2.7, 2.9, 3.1]