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
).