Skip to content

To take multiple variables as input in python

  • To take a string as an input, we can use input() function

    >>> some_var = input()
    1 2 3 4 5
    >>> some_var
    '1 2 3 4 5'
    >>>
    
  • Now we can use split() function to convert a string to list

    >>> some_var = input().split()
    1 2 3 4 5
    >>> some_var
    ['1', '2', '3', '4', '5']
    >>>
    
  • Also we can assign list items to multiple variables in a single line

    >>> a, b, c, d, e = input().split()
    1 2 3 4 5
    >>> a
    '1'
    >>> b
    '2'
    >>> c
    '3'
    >>> d
    '4'
    >>> e
    '5'
    >>>
    
  • When we take a variables as input using input() function, python stores it as string. So if we would like to take multiple variables as input as integers, we would have to take input as string, then convert them into integers.

    >>> a, b, c, d, e = input().split()
    1 2 3 4 5
    >>> a = int(a)
    >>> a
    1
    >>> b = int(b)
    >>> b
    2
    >>> c = int(c)
    >>> c
    3
    >>> d = int(d)
    >>> d
    4
    >>> e = int(e)
    >>> e
    5
    >>>
    
  • We can do this in a single line using map() function.

    >>> a, b, c, d, e = list(map(int, input().split()))
    1 2 3 4 5
    >>> a
    1
    >>> b
    2
    >>> c
    3
    >>> d
    4
    >>> e
    5
    >>>
    
Back to top