Home > Software design >  Filtering a list of strings
Filtering a list of strings

Time:12-13

The problem has the following parameters:

Write a function called only_a that takes in a list of strings and returns a list of strings that contain the letter 'a'.

This is code I am trying to use:

def only_a(starting_list):
  i = 'a'
  final_list = ()
  
  for char in starting_list:
    if i in starting_list:
      final_list = final_list   starting_list.append[0]
  return final_list

t_string_list = ['I like apples', 'I like tea', 'I don\'t', 'Never']
print(only_a(t_string_list))

I keep getting () as a result.

CodePudding user response:

You should a bit change your solution to have it works:

def only_a(starting_list):
  i = 'a'
  final_list = []
  
  for char in starting_list:
    if i in char:
      final_list.append(char)
  return final_list

t_string_list = ['I like apples', 'I like tea', 'I don\'t', 'Never']
print(only_a(t_string_list))

CodePudding user response:

There is a confusion of types here.

() is a tuple, [] is a list, and

final_list = final_list starting_list.append[0] is treating final_list as a string since you are concatenating(adding) another presumably string. But

starting_list.append[0] errors are that append is not an attribute of starting_list and/or that the append list function is not subscriptable(can't be indexed). anotherlist.append(alist[0]) appends the value in alist at [0] to anotherlist.

[0] only gets you a value at index 0 of a string or tuple or list

this is why you are getting an empty tuple but I am surprised it gets that far.

for char in starting_list: implies that you are thinking of the list as a string instead of a list of strings.

So a suggestion to explore the different types in Python.

  • Related