0

A lot of the sample programs out there have this type of code for getting an input:

W = [int(_) for _ in input().split()]

Can someone please explain what is going on in that statement? I can't make sense of it as a whole, but I know what the functions are doing individually.

Top Questions
  • 1,862
  • 4
  • 26
  • 38
shogun000
  • 303
  • 1
  • 2
  • 13
  • If you understand what each part does, what part of the combination is confusing you? – Barmar Jan 19 '15 at 13:39
  • 1
    Your question is too broad; I closed it as a duplicate of the canonical *what's this loop thing in brackets* post. The `input()`, `int()` and `str.split()` methods are all well documented and easy enough to find. – Martijn Pieters Jan 19 '15 at 13:39
  • Thank you, I did try searching first, but I didn't know what keywords to use. – shogun000 Jan 19 '15 at 13:39
  • 1
    Note that using `_` as the name for an object you are going to be using is not very Pythonic; typically, the underscore is used to indicate that the value won't be used. – jonrsharpe Jan 19 '15 at 13:40
  • I still don't understand the use of the _ – shogun000 Jan 19 '15 at 13:40
  • @Barmar: it's a *what does the loop in brackets do* question. E.g. the question to which the answer is: *list comprehension*. – Martijn Pieters Jan 19 '15 at 13:40
  • @shogun000 it's just a name like any other - the code would work the same if you replaced it with e.g. `foo`. – jonrsharpe Jan 19 '15 at 13:40
  • `_` is *just a name*, but in a loop context that would normally be used to mean *this value is going to be ignored*, by convention. This code breaks that convention by using `_` anyway. I'd have used `part` here, or something similarly descriptive: `[int(part) for part in input().split()]` – Martijn Pieters Jan 19 '15 at 13:41

1 Answers1

0

input() accepts the users input and returns a str

split() will split the string on a delimeter, which by default is on whitespace

The remaining is a list comprehension to convert each of the split string items to int.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218