0

I'm new to Python, so I was hoping somebody could break down the following statement and explain the purpose of each part.

[digit for digit in string.split() if digit.isdigit()][0]

Obviously for digit in string.split() creates a list of substrings by separating the string into elements at each space.

What confuses me is the digit at the very beginning and the if statement at the very end.

Is the very first digit what will be returned if digit.isdigit()?

Why must this statement be wrapped in a list?

I've never seen a for loop and an if statement combined into one statement like this before, but it reminds me of a particular JS syntax: for (condition) // whatever or if (condition) // whatever. However, in JS you can't combine them into a single statement (i.e. for (condition) if (condition) // whatever).

oldboy
  • 5,729
  • 6
  • 38
  • 86
  • 1
    https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions – Eugene Primako Jul 07 '18 at 22:02
  • 1
    This is Python's [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) expression, not a statement. It turns what otherwise would be written with `for` loops and `if` statements into a single expression that evaluates as a list. It isn't necessary to use list comprehension, but it helps to make code more concise and in some cases, easier to read. Please read the official documentation for more details. – blhsing Jul 07 '18 at 22:03
  • @blhsing thx buddy – oldboy Jul 07 '18 at 22:09

1 Answers1

0

This is called a list comprehension. You will find plenty of pages explaining how it works. Just ask you favorite search engine.

Gelineau
  • 2,031
  • 4
  • 20
  • 30