user2696225
user2696225

Reputation: 379

Python3 input() floats list

I apologise if I am missing something simple here, but I don't understand...

list_rho = []
# start some sort of loop
val = input() 
list_rho.extend(val)

With this code I am attempting to create a list of rho values: the user inputs a floating point number. This is then added to the list. e.g. the user inputs the values 0.10, 0.15, 0.20, 0.30, 0.35

However, when I print the list it appears like so:

0,  .,  1,  0,  0,  .,  1,  5,  0,  .,  2,  0,  0,  .,  2,  5,  0,  .,  3,  0,  0,  .,  3,  5

Clearly, not what I want. The same happens if I try enclosing the input value in quotes or converting the user input to a string first.

Can anyone offer an explanation of what/why this is happening?

N.B. I could use a loop for the values of rho, but, the number of decimal places is important in my end use and I know there is no way of precisely representing 0.1 in base 2...

Upvotes: 0

Views: 3778

Answers (2)

desimusxvii
desimusxvii

Reputation: 1094

input() returns a string.

list_rho.extend is expecting a list.

"0, ., 1, 0, 0, ., 1, 5, 0, ., 2, 0, 0, ., 2, 5, 0, ., 3, 0, 0, ., 3, 5" is the input string coerced into a list.

>>> m = "0.10, 0.15, 0.20, 0.30, 0.35"
>>> m
'0.10, 0.15, 0.20, 0.30, 0.35'
>>> n = list(m)
>>> n
['0', '.', '1', '0', ',', ' ', '0', '.', '1', '5', ',', ' ', '0', '.', '2', '0', ',', ' ', '0', '.', '3', '0', ',', ' ', '0', '.', '3', '5']
>>> g = []
>>> g.extend(m)
>>> g
['0', '.', '1', '0', ',', ' ', '0', '.', '1', '5', ',', ' ', '0', '.', '2', '0', ',', ' ', '0', '.', '3', '0', ',', ' ', '0', '.', '3', '5']

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 122150

If you want to keep the strings, you can do:

list_rho.extend(val.split(", "))

or, to convert to floating point numbers:

list_rho.extend(map(float, val.split(", ")))

input always gives you a string, and list.extend iterates over its argument adding each item separately, so list.extend("foo") is equivalent to list.extend(['f', 'o', 'o']):

>>> l = []
>>> l.extend("hello, world")
>>> l
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']

>>> l = []
>>> l.extend("hello, world".split(", ")) # right
>>> l
['hello', 'world']

Upvotes: 3

Related Questions