Manas Chaturvedi
Manas Chaturvedi

Reputation: 5540

Taking dynamic number of inputs from the same line

How can we take dynamic number of inputs from the same line? For example, if N is my number of inputs, and if N = 3, then how can I take in 3 different inputs, all separated by spaces, and store them into 3 different variables?

Now, I know how to take inputs from the same line, provided I know the value of N beforehand. I do so using the following code if my number of inputs are 3, and assign them to variables a, b and c respectively:

a,b,c = map(int,raw_input().split())

However, I can't seem to figure out how I could use this code for assigning dynamic number of inputs to equal number of variables.

Upvotes: 1

Views: 2118

Answers (2)

SMIT PANCHOLI
SMIT PANCHOLI

Reputation: 1

l=[]
mat=[]
n=int(input(""))
for i in range(0,n):
    mat=[int(i) for i in input().split()]  
    l.append(mat)
print(l)

Upvotes: 0

Paul Seeb
Paul Seeb

Reputation: 6146

what about something like storing the items in a list and processing them individually?

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

print "you input:"
for i,input_val in enumerate(list_of_input):
    print "item %d: %d:" % (i, input_val)

    if input_val < 5:
        pass   # do something for certain items
    elif input_val > 10:
        pass   # do something else for other items
    else: 
        pass   # etc

and if you are dead set on having "unique" string variable names for each input (even though you get this same behavior from a numeric list index which is more robust, general, faster and simpler than the following suggestion):

var_names = "abcdefghijklmnopqrstuvwxyz"
named_lookup = dict(zip(var_names, list_of_input))

print named_lookup["c"]

Upvotes: 5

Related Questions