Discussion:
[Tutor] Help with List
Anurag Vyas
2015-07-26 04:34:19 UTC
Permalink
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.
--
Thanks & Regards
Anurag Vyas
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-07-26 08:24:19 UTC
Permalink
Post by Anurag Vyas
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
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Loading...