133k views
1 vote
Write code to create a function that meets the following requirements.

• Accepts a list and a string as parameters.
• Returns a copy of the list that does not include any strings equal to the string parameter.

1 Answer

4 votes

Final answer:

To create a function that removes specific strings from a list, you can iterate through the list and filter out the unwanted strings. Here's an example of how to do this in Python.

Step-by-step explanation:

To create a function that meets the given requirements, you can follow the steps below:

  1. Create an empty list to store the filtered elements.
  2. Iterate through the input list using a for loop.
  3. Inside the loop, check if the current element is equal to the string parameter.
  4. If the element is not equal to the string parameter, append it to the filtered list.
  5. After the loop, return the filtered list.

Here's the code implementation in Python:

def filter_list(lst, string_param):
filtered_lst = []
for element in lst:
if element != string_param:
filtered_lst.append(element)
return filtered_lst

You can test the function by calling it with a list and a string:

my_list = ['apple', 'banana', 'cherry', 'banana', 'date']
result_list = filter_list(my_list, 'banana')
print(result_list)

This code will create a list named my_list and then use the filter_list function to remove the string 'banana' from the list. The resulting list, result_list, will not include any occurrences of 'banana'.

User Parker Hutchinson
by
9.0k points