[Solved] How to add elements in list in for loop? My output is [1,1,1] instead of [1,4,5] [closed]
Your version does not work because index always get the first match. And this code is way cleaner and shorter: def search_for_string(lists,str1): list2=[] for index, value in enumerate(lists): if value==str1: lists[index] = ‘xxxxx’ list2.append(index) return list2 sample_list = [“artichoke”, “turnip”, “tomato”, “potato”, “turnip”, “turnip”, “artichoke”] print(search_for_string(sample_list, “turnip”)) Output : C:\Users\Documents>py test.py [1, 4, 5] solved … Read more