62.6k views
1 vote
The function below takes a single argument: data_list, a list containing a mix of strings and numbers. The function tries to use the Filter pattern to filter the list in order to return a new list which contains only strings longer than five characters. The current implementation breaks when it encounters integers in the list. Fix it to return a properly filtered new list.student.py HNM 1 - Hef filter_only_certain_strings (data_list): new_list = [] for data in data_list: if type (data) == str and len(data) >= 5: new_list.append(data) return new_list Restore original file Save & Grade Save only

User Walkiria
by
5.3k points

1 Answer

2 votes

Answer:

Step-by-step explanation:

The Python code that is provided in the question is correct just badly formatted. The snippet of code that states

return new_list

is badly indented and is being accidentally called inside the if statement. This is causing the function to end right after the first element on the list regardless of what type of data it is. In order for the code to work this line needs have the indentation removed so that it lines up with the for loop. like so... and you can see the correct output in the attached picture below.

def filter_only_certain_strings(data_list):

new_list = []

for data in data_list:

if type(data) == str and len(data) >= 5:

new_list.append(data)

return new_list

The function below takes a single argument: data_list, a list containing a mix of-example-1
User NathanPB
by
6.5k points