Taking individual values from a line-python

Hi,
I have recently shifted from C++ to Python. One very common I used in C++ for questions that had logic like

Take input of integers one at a time and perform operations on them

For example, I have to substract every number given in a line(2 3 4 5 …) from a common number and print the value. In C++ we could do it like:

while(N--){
cin  x;
cout  x - k " ";
}

How do I achieve the same in Python, I don’t want to store the values in a list or array, I want to take the values one at a time(using for loop)? Also how can I insert ‘>’ and ‘<’ while using code formatting?

Python input

If numbers are on the same line you can parse the line and loop over it. There are a lot of ways of doing it. You can read the line into a list of integers using a list comprehension

A = [int(x) for x in input().split()]

and then either doing a loop by index, value, or both

for a in A:
    # loops over values in A
for i in range(len(A)):
    # loops over indices
for i,a in enumerate(A):
    # loops over both

Note that if you just want to loop over the values and don’t care about keeping them around you can do things like

for a in [int(x) for x in input().split()]:

but if you want to do that there are better options since the above uses O(n) memory when building the list. Better ways are either a generator or a map, which are both lazy in python3 (in python2 maps are actually not lazy)

for a in [int(x) for x in input().split()]:

for a in map(int, input().split()):

For your particular example the code would look something like

for x in map(int, input().split()):
    print(x-k, end=' ')

or something fancier (which also doesn’t print an extra space at the end)

print(*(x-k for x in map(int, input().split()))

Code formatting

Regarding code formatting indenting your code with 4 space should work fine:

cin >> s;
cout << s << endl;

As an example, this last part of the answer is formatted like

Regarding code formatting indenting your code with 4 space should work fine:

    cin >> s;
    cout << s << endl;

As an example, this last part of the answer is formatted like
3 Likes

You can store the whole input in a list, reverse it, and pop the last element each time you need.

import sys
inp = ''.join(sys.stdin.readlines()).split()
inp.reverse()

If you need an integer, use ‘int(inp.pop())’. Similarly, for float, use ‘float(inp.pop())’.
Sample Solution.

If all the inputs are of a similar data type (generally integer type), you can store them as ‘int’ in the stack.

import sys
inp = map(int, ''.join(sys.stdin.readlines()).split())
inp.reverse()

In this case, you can simply use ‘inp.pop()’ to obtain the input.
Sample Solution.

1 Like

That “>” and “<” interpretation is annoying - but I suspect it’s only a preview artifact. You can also use `

...

` blocks instead of the four-space indent; you just won’t get the shaded background.