Yes, the examples given are very different.
The first example effectively says:
Take the string s
, split it by spaces, and then take each word, x
, found and return the minimum value of just the length of x
.
The second example effectively says:
Find the minimum value in the list generated by len(x) for x in s.split()
.
That first example generates an error because the min
function expects to compare at least 2 or more elements, and only 1 is provided.
That second example works because the list that is generated by len(x) for x in s.split()
converts a string, like say "Python types with ducks?"
to a list of word lengths (in my example, it would convert the string to [6, 5, 4, 6]
). That list that is generated (this is also why it's called a generator), is what the min
function then uses to find the minimum value inside said list.
Another way to write that first example so that it works like you would expect is like this
def find_short(s):
min_length = float("inf")
for x in s.split():
if len(x) < min_length:
min_length = len(x)
return min_length
However, notice how you have to keep track of a variable that you do not have to define using the list generator method in your second example. Although this is not a big deal when you are learning programming for the first time, it becomes a bigger deal when you start making larger, more complex programs.
Sidenote:
Any value that follows the return
keyword is what a function "outputs", and thus no more code gets executed.
For example, in your first example (and assuming that the error was not generated), your loop would only ever execute once regardless of the string you give it because it does not check that you actually have found the value you want. What I mean by that is that any time your code encounters a return
statement, it means that your function is done.
That is why in my example find_short
function, I have an if
statement to check that I have the value that I want before committing to the return
statement that exits the function entirely.