I require some help on how to go about writing a function that removes an item from a list along with how to return a list with an item removed. Any help would be gladly appreciated.

Recommended Answers

All 2 Replies

you can use the list.remove function

list = ['sp','am',' and', ' eggs']
list.remove(' eggs')
print(list)

Have you tryed som yourself,and mayby post some code.
Can take a little about this but next time dont expext to get help if you dont but some effort in to this.

>>> lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
>>> dir(lst)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> help(lst.remove)
Help on built-in function remove:

remove(...)
    L.remove(value) -- remove first occurrence of value.
    Raises ValueError if the value is not present.

>>> lst.remove('apples')
>>> lst
['bunnies', 'animals', 'fruit', 'amsterdam']
>>> #To remove item in a list by index use del
>>> lst.index('fruit')
2
>>> del lst[2]
>>> lst
['bunnies', 'animals', 'amsterdam']
>>>

One commen way to remove items for a list is to iterate over list and remove stuff.
This also made opp for some commen mistake.
Let look at this.

lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
for item in lst:
	if item[0] == 'a':
            lst.remove(item)
print lst
'''my ouyput-->
['bunnies', 'animals', 'fruit']
'''

This is wrong it dont remove 'animals' that has 'a' as item[0]
This is because index get wrong, if you not first make a copy of that list.

>>> lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
>>> new_list = lst[:]
>>> new_list
['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']

Then we can write it like this.

lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']
for item in lst[:]:
	if item[0] == 'a':
            lst.remove(item)
print lst
'''my output-->
['bunnies', 'fruit']

Or we append to a new list.

lst = ['bunnies', 'apples', 'animals', 'fruit', 'amsterdam']    
new_list = []
for item in lst:
    if item[0] != 'a':
        new_list.append(item)
print new_list
'''my output
['bunnies', 'fruit']
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.