I am working on the exercises for python from Google and I can’t figure out why I am not getting the correct answer for a list problem. I saw the solution and they did it differently then me but I think the way I did it should work also.
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
# +++your code here+++
list = []
xlist = []
for word in words:
list.append(word)
list.sort()
for s in list:
if s.startswith('x'):
xlist.append(s)
list.remove(s)
return xlist+list
The call is:
front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa'])
I get:
[‘xaa’, ‘axx’, ‘bbb’, ‘ccc’, ‘xzz’]
when the answer should be:
[‘xaa’, ‘xzz’, ‘axx’, ‘b
bb’, ‘ccc’]
I’ve don’t understand why my solution does not work
Thank you.
You shouldn’t modify a list while iterating over it. See the
forstatement documentation.