2
import numpy
n,m=map(int, input().split())
arr=numpy.array([input().strip().split() for _ in range(n)],int)
print (numpy.transpose(arr))
print(arr.flatten())

Why should there be an underscore before "in range" in the third line? It would also be useful if someone explained why .strip and .split need to be applied here. Thanks a lot!

2 Answers2

1

_ is just a variable, it could be named differently, for example i. _ is just a conventional name for unused variables. In this case, you execute input().strip().split() n times in exactly the same way, without caring which iteration (i) it is.

.split() splits the input string by spaces, for example:

>>> '1 2 3'.split()
['1', '2', '3']

.strip() trims whitespace at the edges:

>>> '  1 2 3 '.strip()
'1 2 3'

You can read more about these methods by googling the docs or, even simpler, running help(str.split) in an inerpreter

Expurple
  • 877
  • 6
  • 13
0

In Python, the underscore holds the result of the last executed expression.

In some cases, it is used to replace a variable that will not be used.

In your example, as you just need to loop n number of times without needing to know the value of each iteration, you can use for _ in range(n) instead of for i in range(n).

You can find more information about the underscore in Python here: What is the purpose of the single underscore "_" variable in Python?


As for the strip and split methods, here is a quick explanation based on the Python documentation.

str.strip: Return a copy of the string with the leading and trailing characters removed. str.split: Return a list of the words in the string, using sep as the delimiter string.

So from your example, your code takes the input of the user, removes any leading and trailing characters with strip, and split the input into a list of words.

For example, if the user input is Hello World! , the result will be: ["Hello", "World!"]

Hope that helps!

Antoine Delia
  • 1,728
  • 5
  • 26
  • 42