0

I have two lists and want to check if elements from first list are in the second list. If true, I want to remove the matched element from a copy of my first list.

my_list = [ 
    '100a',
    '100b',
    '100c'
]
    
your_list = [
    '100a_nnb',
    '100b_ub',
    '100c_AGGtb'
]

my_list_2 = my_list


for i in my_list:
    for j in your_list:
        if i in j:
            print(f'Yes, {i} is in {j}!')
            #my_list_2.remove(i)
            break
        else:
            print(f'No, {i} is not in {j}!')

When I leave my_list_2.remove(i) comment out, I got as expected:

Yes, 100a is in 100a_nnb!
No, 100b is not in 100a_nnb! 
Yes, 100b is in 100b_ub!
No, 100c is not in 100a_nnb!
No, 100c is not in 100b_ub!
Yes, 100c is in 100c_AGGtb!

When I remove # it gives me:

Yes, 100a is in 100a_nnb!
No, 100c is not in 100a_nnb!
No, 100c is not in 100b_ub!
Yes, 100c is in 100c_AGGtb!

Why is that? It seems that it skips every second list item.

martineau
  • 119,623
  • 25
  • 170
  • 301
ktw
  • 98
  • 9

2 Answers2

0

The problem is with this line used to create the copy of the first list. Rather than creating a copy, here both variables refer to the same list in memory.

my_list_2 = my_list

As a result, you are removing the values from the original list, when you remove the values from the "copied" list.

In order to create a copy of the original list, use the copy() method

my_list_2 = my_list.copy()
tintins7a6164
  • 188
  • 1
  • 7
0

Solution

[ i ]: my_list_2 = my_list.copy()

[ ii ]: my_list_2 = my_list[::]

Notes:

by following you are just referencing my_list_2 to my_list.

my_list_2 = my_list

if you ll do check id(my_list_2) and id(my_list) you ll have the same id.

shivankgtm
  • 1,207
  • 1
  • 9
  • 20
  • 1
    Found a very good explanation and comparison after your answer. [ii] seems to be the fastest way to copy one list to another. https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it – ktw Dec 19 '21 at 01:20