0

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.

Awesh
  • 51
  • 8
  • `l1` is a reference to a list in memory. If you never change what object in memory is referenced, then all actions you perform are on that variable are to the same object. Any references you created to that same object (i.e. `l11.append(l1)`) will correspondingly continue to reflect the state of that object. You need to review object references in Python. note that `l1 =` is an assignment and thus changes the object that `l1` is referencing. – tehhowch Aug 24 '18 at 19:45
  • 1
    I can never find the dupe target for this one when it comes up... in short, the difference is that in the first one you're appending four references to the same list, so as you change the contents of `l1`, all elements of `l11` change accordingly. In the second example you properly create and append a new list each time. – glibdud Aug 24 '18 at 19:45
  • In the first case, you are re-using the same list object, so obviously the list object will always have the same values as itself. In the second case, you are creating new, independent list objects that may have different values. The current duplicate target isn't the greatest fit, I'll try to find a better target, but the underlying problem is the same. – juanpa.arrivillaga Aug 24 '18 at 20:18

1 Answers1

0

In the first function, you are appending 3 reference of the same list object.

In the second function, you created 3 list object and append them in the final result.

enter image description here You can use this visualization tool to see what I mean. pythontutor

Q. Qiao
  • 767
  • 6
  • 17