Moving Places, Subtracting from slices/lists

Elliot Temple curi at curi.us
Thu Jun 2 03:39:37 EDT 2005


On Jun 2, 2005, at 12:12 AM, Mark Sargent wrote:

> Hi All,
>
> getting closer, me thinks.
>
>
>>>> hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin']
>>>> for x in hotcat[:]:
>>>>
> ...     if x == 'roof': hotcat.insert(6,x)
> ...     del hotcat[x]
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 3, in ?
> TypeError: list indices must be integers
>
> How do I get that x to be an integer b4 it is entered into the  
> indice.?
> Cheers.

if you add "print x" to the loop you will see that X is the various  
words.

to get an integer, you could search the list for the index of x.  but  
that's lame.

btw hotcat[:] is a *copy* of hotcat, so just leave out "[:]"

enumerate is a function that adds indexes to a list.  observe:

hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin']
for index, word in enumerate(hotcat):
     if word == 'roof': del hotcat[index]

you could also use a list comprehension

hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin']
hotcat = [x for x in hotcat if x != 'roof']

-- Elliot Temple
http://www.curi.us/


---
[This E-mail scanned for viruses by Declude Virus]




More information about the Python-list mailing list