0

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...

2 Answers 2

3

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']
Sign up to request clarification or add additional context in comments.

Comments

0

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']

1 Comment

list.extend expects an iterable object, which it gets. It doesn't coerce the str to a list (Python is strongly-typed, and doesn't implicitly coerce); it iterates over it. The problem here is that iterating over a string is done character-by-character, which isn't how the OP wants to interpret the input.

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.