Varun
Varun

Reputation: 1043

List iteration issue in Python

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.

Upvotes: 1

Views: 115

Answers (2)

user1277476
user1277476

Reputation: 2909

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.

Upvotes: 0

Amber
Amber

Reputation: 526623

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.

Upvotes: 8

Related Questions