Performance issue

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat Apr 2 11:30:23 EST 2005


In <mailman.1239.1112456748.1799.python-list at python.org>, Tom Carrick
wrote:

> […] Also, I was wondering if there was a more
> builtin, or just nicer way of converting a string to a list (or using
> the sort function on a list) than making a function for it.

Use the `list()` builtin on the string and *just* the `sort()` method::

  In [2]: characters = list('hello')

  In [3]: characters
  Out[3]: ['h', 'e', 'l', 'l', 'o']

  In [4]: characters.sort()

  In [5]: characters
  Out[5]: ['e', 'h', 'l', 'l', 'o']

> sorted_anagram = anagram.lower()
> sorted_anagram = string2list(anagram)
> sorted_anagram.sort(lambda x, y: cmp(x, y))

sorted_anagram = list(anagram.lower())
sorted_anagram.sort()

> while words:
>     if len(words[0]) == len(sorted_anagram):
>         wordlist = string2list(words[0])
>         wordlist.sort(lambda x, y: cmp(x, y))
>         sorted_wordlist = wordlist
>         if sorted_anagram == sorted_wordlist:
>             found.append(words[0])
>     del words[0]

And here's the performance issue.  Deleting the first element of a list
results in moving all remaining elements one index down.  Better iterate
over the words in a for loop::

  for word in words:
    # use `word` instead of `word[0]` in the loop body.
    ...

Ciao,
	Marc 'BlackJack' Rintsch




More information about the Python-list mailing list