is there a better way?

Jeremy Dillworth jdillworth at gmail.com
Fri Feb 10 16:31:11 EST 2006


You could eliminate a few lines like this:

-----------------------------
while list and list[0] != O:
    storage.append(list.pop(0))
-----------------------------

Adding the "list and " to the front of the logic test will catch when
there are 0 elements, so the "if..break" lines are not needed.  Also
pop() returns the element popped, so there's no need for a separate
"list[0]" and "list.pop(0)"

You could also do the whole thing as a list comprehension (assuming
storage is a list, otherwise += may or may not work):
-----------------------------
storage += [i for i in list if i == X]
-----------------------------

But this is less efficient, since it will loop through all the O's too.
 The other solution stops at the first O.  This will also break if
there are any X's mixed with O's, though you've said that's not
currently the case, things can always change.

Lastly, you could do this:
-----------------------------
list.append(O)
storage += list[:list.index(O)]
-----------------------------

The first line makes sure there is always an O in list, otherwise
index(O) will throw an exception.  That's slightly ugly, but I still
like this solution, myself.

hope this helps,

Jeremy




More information about the Python-list mailing list