1

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.

5
  • new here, want to know how to do that? Commented Apr 10, 2012 at 22:04
  • Check this portion of the FAQ. Commented 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". Commented Apr 10, 2012 at 22:06
  • Thanks, Got it, I will start doing that. Commented 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. Commented Apr 10, 2012 at 22:33

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.