[Tutor] Help with List
Steven D'Aprano
steve at pearwood.info
Sun Jul 26 10:24:19 CEST 2015
On Sun, Jul 26, 2015 at 10:04:19AM +0530, Anurag Vyas wrote:
> Hello Team,
> I am noob to programming. I am trying to remove a item from a list. The
> item that I am trying to remove has multiple entries in the list. I am not
> able to remove all the entries.
> Please Help. The code is in the attachment.
There is no attachment. Perhaps you forgot to attach it?
In general, if your code is less than 20 or 30 lines, you should just
include it in the body of your email. If your code is more than 30
lines, you should simplify it so that it is smaller.
To delete a single item from a list:
alist = ['a', 'b', 'c', 'd', 'e']
alist.remove('b')
To delete multiple entries with the same value:
alist = ['a', 'b', 'c', 'b', 'd', 'b', 'e', 'b', 'b']
try:
while True:
alist.remove('b')
except ValueError:
pass
but this will probably be more efficient:
alist = ['a', 'b', 'c', 'b', 'd', 'b', 'e', 'b', 'b']
alist = [item for item in alist if item != 'b']
That last one is called a "list comprehension", and is a short cut for a
for-loop like this:
tmp = []
for item in alist:
if item != 'b':
tmp.append(item)
alist = tmp
--
Steve
More information about the Tutor
mailing list