[Tutor] Re: Printing two elements in a list

C Smith smichr at hotmail.com
Mon Dec 20 06:29:22 CET 2004


Jacob S. wrote:

> Would this work for you?
>
> a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
> for index,thing in enumerate(a):
>     if "Name=" in thing:
>         del a[index]
>
> I know, that it might be slow, but I thought that maybe it would hold 
> its
> own because it doesn't have to import the re module, everything's 
> builtin,
> etc.
>
Be careful here, the above code will miss deleting an element 
containing "Name=" if there are two in a row.  Look at this simple 
example where we attempt to delete elements equal to 2:

###

 >>> a=[1,2,1,2]
 >>> for i,x in enumerate(a):
..  if x==2:del a[i]
..
 >>> a
[1, 1]
 >>> #
 >>> # ok that looks right, but watch this
 >>> #
 >>> b=[2,2,1,1]
 >>> for i,x in enumerate(b):
..   if x==2: del b[i]
..
 >>> b
[2, 1, 1]

###

After deleting element 0 in b, all the elements "slid down" one place 
and the 2nd 2 that was in b is now in position 0...but you are moving 
on to index 1 with the enumerate loop:

[2, 2, 1, 1]
  ^
  enumerate is at index 0

we delete element 0

[2, 1, 1]
     ^
     enumerate is at index 1 and the 2 that was at position 1 is now at 
position 0

An alternative is to use a list comprehension, keeping only the 
elements that are not 2. As is shown, you can replace the list you are 
filtering with the filtered result:

###

 >>> b=[2,2,1,1]
 >>> b=[x for x in b if not(x==2)]
 >>> b
[1, 1]

###

/c




More information about the Tutor mailing list