How to read two numeric values for a list in the same line in Python?

Asked

Viewed 138 times

0

I know that to read multiple values by input on the same line you use "split()", and to add values to lists, some loop like "for" or "while"but I would like to know how to join both to be able to add multiple numeric values to a list having all of these inserted by just one line. I tried something like:

c = 0
n = input()
while c < n:
    X.append(c,input().split(' '))
    c+=1

But it doesn’t work, so if anyone knows any solution, please say,.

    1. At least for me, your doubt is unclear. You wrote a four-line sentence! Try reformulating the text, explaining better each of the points you are presenting. 2) Where you have defined X?
  • Mate, I can’t answer your question, you want a flat list or a list of tuples of size n ?

1 answer

1


Use the method extend() that extends a list with the content of the argument.

As in the question you say "multiple numeric values" use list comprehensions to convert the string for int

>>> x = [0, 1]
>>> x.extend([int(i) for i in input().split(' ')])
2 3 4 5 6
>>> print(x)
[0, 1, 2, 3, 4, 5, 6]

It is also possible to achieve the same result using the composite allocation operator += instead of extend().

>>> x = [0, 1]
>>> x += [int(i) for i in input().split(' ')]
2 3 4 5 6
>>> print(x)
[0, 1, 2, 3, 4, 5, 6]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.