10
\$\begingroup\$

I'm new to programming in general, started on boxing day. I'm trying to learn python. The list remove method only removes the first instance of the value found.
In the code below I attempted to remove all the instances. Are there better ways of accomplishing this? Is this efficient? Any and all feedback is wanted.

wordlist = ["dog", "cat", "mouse", "giraffe", "cat"]
remove_queue = []
userinput = input("remove: ")
for i in range(len(wordlist)):
    if wordlist[i] == userinput:
        remove_queue.append(i)

""""reversed the list, so when deleting a value, the position of the other 
values don't change"""
remove_queue.sort(reverse=True)
for i in range(len(remove_queue)):

"""uses the remove_queue list to find the position of value that needs to be 
removed, and removes it. """
    del wordlist[remove_queue[i]]
print(wordlist)
\$\endgroup\$
8
\$\begingroup\$

Iterating backwards was smart, but, yes, there is a much simpler way to do this using a list comprehension – this is how one typically filters a list in Python.

filtered_words = [word for word in word_list if word != user_input]

Note that this creates a new list object rather than altering the original word list in place.

Your current code isn't terribly inefficient – it iterates over the list twice rather than once, but both are asymptotically linear.

If you were to keep that structure, there are a number of small things that could be done to make the code more Pythonic. Compare the following loops to your own code:

for i, word in enumerate(word_list):
    if word == user_input:
        remove_queue.append(i)

for i in remove_queue[::-1]:
    del word_list[i]

These do the same thing, but are much more readable once one knows that enumerate can be used to iterate over both the index and element at once and that list[::-1] is a common method to iterate over a list backwards (albeit, slightly inefficient).

A final note is that I have updated all two-word names to use snake-case.

\$\endgroup\$
  • \$\begingroup\$ I think the sorting is essential. I haven't tried your solution, but I think it suffers what the OP was trying to avoid by sorting the list. Try your solution by entering multiple values to remove i.e. the remove_queue contains more than one item \$\endgroup\$ – smac89 Dec 29 '17 at 0:06
  • \$\begingroup\$ @smac89 The list will be sorted to begin with because the indices are added in order. \$\endgroup\$ – Jared Goguen Dec 29 '17 at 4:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.