Actually I wrote a code to find a character from the list and print the index but am not getting the difference between these two codes please help me out:
#My list:
l = ["MA-%78*%%1","MA%-78*%1","MA%%-%78*1","M%A#-78*%%1"]
search(l,"%")
Code 1:
def search(string_list,search_character):
sl = string_list
char1 = search_character
l1 = list()
l11 = list()
for j in range(len(string_list)):
l1.clear()
s1 = string_list[j]
for i in range(len(s1)):
if s1[i] == search_character:
l1.append(i+1)
l11.append(l1)
return l11
This yields the output:
[[1, 8, 9], [1, 8, 9], [1, 8, 9], [1, 8, 9]]
Code 2:
def search(string_list,search_character):
sl = string_list
char1 = search_character
l11 = list()
for j in range(len(string_list)):
l1 = list()
s1 = string_list[j]
for i in range(len(s1)):
if s1[i] == search_character:
l1.append(i+1)
l11.append(l1)
return l11
I get correct output when I initialized the list again without clearing it:
[[4, 8, 9], [3, 8], [3, 4, 6], [2, 9, 10]]
I didn't understood what is wrong with l1.clear()
function.