# [Tutor] a question about list

Max Noel maxnoel_fr at yahoo.fr
Fri Nov 12 01:06:54 CET 2004

```On Nov 11, 2004, at 23:43, Terry Carroll wrote:

> On Thu, 11 Nov 2004, Max Noel wrote:
>
>> a = [element for index, element in enumerate(a) if index not in b]
>
> Damn, and I thought I was starting to get list comprehensions; but
> this is
> impenetrable to me.
>
> That's not a criticism; more a statement on my inability to get list
> comprehensions.
>
> Would you mind unwrapping and explaining this a bit?  I'd like to
> understand it better.

Sure, no problems.
The cornerstone of this list comprehension is enumerate(a). This is
basically an iterator that yields (index, element) tuples. In other
words,
>>> blah = ['a', 'b', 'c', 'd']
>>> for index, element in enumerate(foo):
...     print "%s -> %s" % (index, element)
...
0 -> a
1 -> b
2 -> c
3 -> d

So if my list comprehension were:

a = [element for index, element in enumerate(a)]

It would be equivalent to assigning to a a copy of itself. However,
the great thing about list comprehensions is that you can specify a
condition that an element has to match to be added to the list, some
sort of filter. Here's an example:

>>> foo = [0, 1, 2, 0, 3, 0, 4, 0, 5]
>>> bar = [element for element in foo if element != 0]
>>> bar
[1, 2, 3, 4, 5]

If element is equal to zero, it is not added to the resulting list.

Still following (I know, I'm not very good at explaining)? If so, you
should be starting to get my original list comprehension, which is:

a = [element for index, element in enumerate(a) if index not in b]

Here, I'm iterating over two variables: for each element of the
original list a, index contains its index and element contains the
value of the element itself (yeah, I like to use explicit names).
Besides, b contains the indexes of the elements which we want to
delete from a, i.e. the indexes of the elements which we don't want in
the resulting list. Therefore, the condition if index not in b filters
out the elements whose indexes are elements of b.
In the original example, b = [1, 2, 4]. Thus, the elements in a whose
indexes are 1, 2 or 4 are filtered out.

Did that help?

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting
and sweating as you run through my corridors... How can you challenge a
perfect, immortal machine?"

```