I am working with Google Python class exercises where I am getting this issue -
def front_x(words):
# +++your code here+++
list = []
for i,s in enumerate(words):
print i,s
if s[0] == 'x':
list.append(words.pop(i))
return list
print front_x(['bbb','ccc','axx','xzz','xaa'])
my loop is only iterating from 0 to 3, so print i,s is giving me values till 'xzz'.Please point where I am wrong.
-
new here, want to know how to do that?Varun– Varun2012年04月10日 22:04:31 +00:00Commented Apr 10, 2012 at 22:04
-
Check this portion of the FAQ.Makoto– Makoto2012年04月10日 22:05:29 +00:00Commented Apr 10, 2012 at 22:05
-
Each answer to question you've asked has a "tick" below the vote counter. When you click it, you basically say "This answer was correct from my POV".Stan– Stan2012年04月10日 22:06:16 +00:00Commented Apr 10, 2012 at 22:06
-
Thanks, Got it, I will start doing that.Varun– Varun2012年04月10日 22:07:46 +00:00Commented Apr 10, 2012 at 22:07
-
1@Varun: You can also go back to previous questions and click off on the correct answers. It won't take very long, and it will help out the people who helped you.Steven Rumbalski– Steven Rumbalski2012年04月10日 22:33:48 +00:00Commented Apr 10, 2012 at 22:33
2 Answers 2
Don't modify something as you're iterating over it. words.pop(i) modifies words, which you're iterating over via enumerate().
I'd suggest looking at list comprehensions for accomplishing your apparent goal.
Comments
Yes, you probably shouldn't words.pop(). The word you want is most likely in s - add that to the list instead.
Also, note that naming a list "list", will more or less erase the "list" builtin type from your local scope. It's not a make or break kind of deal, but it's something pylint would warn about.