Home > Enterprise >  list.remove() within nested for loops
list.remove() within nested for loops

Time:12-19

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.

CodePudding user response:

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.

CodePudding user response:

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()
  • Related