[Tutor] removing items from a list

Yigal Duppen yduppen@xs4all.nl
Sat, 12 Oct 2002 12:50:46 +0200


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Saturday 12 October 2002 09:42, Galen O'Neil wrote:
> Dear listreaders,
> I want to remove items from a list that have content that matches my
> data.  I can think of a few ways to do this, but none that seem as
> simple as it should be.

Simplest solution:
>>> item = "a"
>>> l = ["a", "b", "c"]
>>> l.remove(item)
>>> l
['b', 'c']

Note: remove will only remove the *first* value from the list

> This doesn't work, I'm not sure why.  Mabye item isn't a refence to the
> list item, but just has the same value.
>
> for item in list:
> 	if item == data: del item

Some notes:
1. Never use a built-in name such as list (or dict, or file, or...) for a 
variable. That's asking for trouble :)

2. What happens is this:
example:
>>> item = "a"			# The value "a" is given the name 'item'
>>> l = ["a", "b", "c"]		# A new object is created which contains "a", "b" and
					# "c". This new object gets the name 'l'
>>> del item			# The name 'item' is removed. The value it refers to is 
					# *not* removed!

Have fun!
YDD
- -- 
http://www.xs4all.nl/~yduppen
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.0 (GNU/Linux)

iD8DBQE9p/6GLsKMuCf5EdwRAhHjAJ92BlRQ7BMc+v5Y8oVFgbtV7fcN0QCaAnkx
0GjUvRwmBY7NnFOoU+9sDQE=
=x7UY
-----END PGP SIGNATURE-----