[Tutor] using a for loop in another method
Michael Selik
michael.selik at gmail.com
Fri Apr 22 16:31:02 EDT 2016
On Fri, Apr 22, 2016 at 1:57 PM Rene.Castillo <jackalren at gmail.com> wrote:
> expected output-
> reverse_words("This is an example!") # returns "sihT si na !elpmaxe"
>
> def reverse_words(strng):
> strng = strng[::-1].split(' ')
> strng.reverse()
> return ' '.join(strng)
>
Let's walk through each step that you wrote. First, I'd rather use the
variable name ``s`` than ``strng``. It's just as readable in small snippets
of code like this.
``s`` gets passed in. We'll go ahead and assume it's a str, or something
str-like. There's no need to check the type. That's for more paranoid
languages.
s = s[::-1].split()
This reverses the string via slicing, then splits on whitespace, assigning
the resulting list back over the variable ``s``. If ``s`` (or previously,
``strng``) suggests that the variable refers to a str, we now have some
confusion as it's referring to a list, not a str.
s.reverse()
In-place reversal of a list. When I see this line without paying attention,
I think it's a bug. The str type does not have a reverse method! But of
course, I was misled by the variable name and the code indeed works.
' '.join(s)
Again, this looks like a bug, but since ``s`` is a list, it works just fine.
Now let's look at your friend's code, which actually has a little bug in it.
' '.join( ... )
We already know what that does, joins a list of strings on a ' ' separator.
s[::-1] for s in str.split(' ')
Looking at the first bit, there's a ``s[::-1]`` so that must reverse a
string. Then there's ``for s in ...`` and that looks like a regular
for-loop, assigning to a variable ``s`` for each iteration. And finally,
``str.split(' ')`` is where we find the bug. They probably meant
``strng.split()`` and intended to keep the parameter named ``strng``.
There's no need to pass any input to the split method, as it splits on
whitespace by default.
Tim Golden already mentioned that this technique is a comprehension. It is
equivalent to writing like this:
def reverse_words(sentence):
reversals = []
for word in sentence.split():
reversals.append(word[::-1])
return ' '.join(reversals)
Note how using more meaningful variable names avoids confusion. Instead of
using names like "intgr" or "strng" you should probably name things after
their meanings instead of their data types.
> def reverse_words(s)
> return ' '.join(s[::-1] for s in str.split(' '))
>
>
>
> how can a for loop be called within another method like that- and possibly
> what situations does this benefit
> i don't even know how to google this sort of thing
> any words are appreciated-
>
>
>
> R
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list