[Tutor] Working with lists - why does my script not work?

Puneeth Chaganti punchagan at gmail.com
Mon Jun 25 15:39:54 CEST 2012


On Mon, Jun 25, 2012 at 6:51 PM, Developer Ecofunds
<ecofunds.developer at gmail.com> wrote:
> Hello guys,
>
> I'd like to ask you a little question about a script I did and isn't working
> properly.
> It is one excercise from googles python classes
> <http://code.google.com/edu/languages/google-python-class/set-up.html>
>
> I'm using python 2.5 because it's the one works with Google App Engine
> <https://developers.google.com/appengine/docs/python/gettingstarted/>
>
> This is the problem:
>
> ##########################3
>
> # 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.
>
> # This is the code I did -- Romulo.
>
> def front_x(words):
>   x_list = []
>   for string in words:
>     if string[0]=='x':
>       x_list.append(string)
>       words.remove(string)
>   sorted(words)
>   sorted(x_list)

`sorted`[0] returns a new list unlike `sort`[1], which sorts a list in-place.

Something like this, would work:

words = sorted(words)
x_list = sorted(x_list)

Also, in your code, you are changing the `words` list, while you are
iterating over it, and this will cause problems while you iterate over
the list.  Generate a copy of the list and iterate over it by
iterating over `words[:]` instead of `words`.

Hope that helps,
Puneeth

[0] - http://docs.python.org/library/functions.html#sorted
[1] - http://docs.python.org/tutorial/datastructures.html#more-on-lists


More information about the Tutor mailing list