-5

I am trying to create a piece of code that allows me to ask the user to enter 5 numbers at once that will be stored into a list. For instance the code would would be ran and something like this would appear in the shell

Please enter five numbers separated by a single space only:

To which the user could reply like this

 1 2 3 4 5 

And then the numbers 1 2 3 4 5 would be stored into a list as integer values that could be called on later in the program.

vaultah
  • 44,105
  • 12
  • 114
  • 143
FCBHokie
  • 7
  • 1
  • 1
  • 5

5 Answers5

1

You can use something like this:

my_list = input("Please enter five numbers separated by a single space only")
my_list = my_list.split(' ')
1

Your best way of doing this, is probably going to be a list comprehension.

user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]

This will split the user's input at the spaces, and create an integer list.

Zach Gates
  • 4,045
  • 1
  • 27
  • 51
0

This could be achieved very easily by using the raw_input() function and then convert them to a list of string using split() and map()

num = map(int,raw_input("enter five numbers separated by a single space only" ).split())
[1, 2, 3, 4, 5]
Daniel
  • 5,095
  • 5
  • 35
  • 48
0

You'll need to use regular expressions as the user may also enter non-integer values as well:

nums = [int(a) for a in re.findall(r'\d+', raw_input('Enter five integers: '))]
nums = nums if len(nums) <= 5 else nums[:5] # cut off the numbers to hold five
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
-1

Here is a subtle way to take user input into a list:

l=list()
while len(l) < 5: # any range
    test=input()
    i=int(test)
    l.append(i)

print(l)

It should be easy enough to understand. Any range range can be applied to the while loop, and simply request a number, one at a time.

armatita
  • 12,825
  • 8
  • 48
  • 49
user3773786
  • 1
  • 1
  • 1