Slicing a list with non-integer parameter? How?
Chris Liechti
cliechti at gmx.net
Sat Oct 6 14:35:18 EDT 2001
Husam <h.jehadalwan at student.kun.nl> wrote in
news:3BBF216D.25524AAB at student.kun.nl:
> Hi fiends,
> I'm trying to determine the position of an item in a list in order to
> delete it by slicing the list with non integer parameter.
> Code I works just fine. But code II doe's not work:
>
> Code 1 with integer values:
>
>>> list1=[1,2,3,4]
>>>> for i in list1:
> ... if i==2:
> ... pos=len(list)-len(list[i:])
> ... del list[pos-1]
> ... print list
> ...
> [1, 3, 4]
for "iterates" over the list, meaning that you get one element after the
other. if your list has strings in it, then "i" is also a string. in your
case you might consider:
for pos in range(len(list)):
item = list[pos]
#...
1. you have an integer to use it as index
2. you dont need to do the "pos" calculation
an other point:
deleting items in the list your working on is usualy a bad idea. its better
when you delete the items in a copy of the list:
copylist = list(origlist)
(don't name your variable "list" as this is a builtin function to convert
something to a list)
and as another poster Wmile van Sebille mentioned already, there is:
list1.remove(element)
which does what you want.
Chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list