Question

So I am taking raw_input as an input for some list.

x= raw_input()

Where I input 1 2 3 4 How will I convert it into a list of integers if I am inputting only numbers?

Was it helpful?

Solution

Like this:

string_input = raw_input()
input_list = string_input.split() #splits the input string on spaces
# process string elements in the list and make them integers
input_list = [int(a) for a in input_list] 

OTHER TIPS

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

We are using a higher order function map to get a list of integers.

You can do the following using eval:

lst = raw_input('Enter your list: ')
lst = eval(lst)
print lst

This runs as:

>>> lst = raw_input('Enter your list: ')
Enter your list: [1, 5, 2, 4]
>>> lst = eval(lst)
>>> print lst
[1, 5, 2, 4]
>>> 

Here are some examples and brief explanation for Inputting Lists from users:

You may often need code that reads data from the console into a list. You can enter one data item per line and append it to a list in a loop. For example, the following code reads ten numbers one per line into a list.

lst1 = [] # Create an empty list
print("Enter 10 Numbers: ")
for i in range(10):
   lst1.append(eval(input()))

print(lst1)

Sometimes it is more convenient to enter the data in one line separated by spaces. You can use the string’s split method to extract data from a line of input. For example, the following code reads ten numbers separated by spaces from one line into a list.

# Read numbers as a string from the console
s = input("Enter 10 numbers separated by spaces from one line: ")
items = s.split() # Extract items from the string
lst2 = [eval(x) for x in items] # Convert items to numbers

print(lst2)

Invoking input() reads a string. Using s.split() extracts the items delimited by spaces from string s and returns items in a list. The last line creates a list of numbers by converting the items into numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top