user1198149
user1198149

Reputation: 33

How to enter all the elements of a list in a single line without going on to new line in Python

I want to enter all the elements of a python list in one single line without pressing Enter.

For Example:

>>> l = []
>>> l = [raw_input() for i in xrange(5)]
1
2
3
4
5

Instead of this I want to enter like

>>> ...
1 2 3 4 5

Any help or pointers will be great.

Upvotes: 2

Views: 513

Answers (4)

pts
pts

Reputation: 87281

This works in a Python script, but not in an interactive interpreter:

l = []
while len(l) < 5:
  l.extend(raw_input().split())
print l

Using this solution, it doesn't matter if you press Enter or not, you can also write a combination of spaces and Enters, but you have to finish with an Enter.

Upvotes: 1

martineg
martineg

Reputation: 1359

If I understand your question correctly, you could just split the result of raw_input(), like this?

>>> raw_input().split()
1 2 3 4 5
-> ['1', '2', '3', '4', '5']

Alternatively do something with the input elements:

[ int(x) for x in raw_input().split()  ]
1 2 3 4 5
-> [1, 2, 3, 4, 5]

Upvotes: 3

Niklas B.
Niklas B.

Reputation: 95308

Bit less verbose:

numbers = map(int, raw_input().split())

Upvotes: 4

nmichaels
nmichaels

Reputation: 50951

>>> text = raw_input()
1 2 3 4 5
>>> numbers = [int(num) for num in text.split()]
>>> numbers
0: [1, 2, 3, 4, 5]

Upvotes: 1

Related Questions