0

I have two lists and I want to search for an item in one list and delete it in the other if it matches. But when I search one list, I don't know how to search the other, so I can only do one search at time. Do you guys know how can I do that?

list_groups = [['john', 'mary', 'peter'],
           ['luh', 'henry', 'maxi'],
           ['patrick', 'juva', 'xavier', 'dorovich']]
list_users = ['peter', 'henry', 'dorovich']

num = 0
num_group = 0

while num < 45:
   user = list_users[num]
   group = list_groups[num_group]
   if user in group:
      group.remove(user)
      print(group)
   else:
      print(f'The user was not find in the group {num}')
      num += 1
   num_group += 1
Timus
  • 10,974
  • 5
  • 14
  • 28
  • 1
    Read this please : https://stackoverflow.com/questions/4211209/remove-all-the-elements-that-occur-in-one-list-from-another – Gedas Miksenas Nov 09 '21 at 13:17

1 Answers1

0

You could use a list comprehension (or a set operation) as suggested in Remove all the elements that occur in one list from another.

Here an example using a list comprehension with your example data:

list_groups = [
    ['john', 'mary', 'peter'],
    ['luh', 'henry', 'maxi'],
    ['patrick', 'juva', 'xavier', 'dorovich']
]
list_users = ['peter', 'henry', 'dorovich']

for i, group in enumerate(list_groups):
    list_groups[i] = [user for user in group if user not in list_users]

print(list_groups)
# [['john', 'mary'], ['luh', 'maxi'], ['patrick', 'juva', 'xavier']]

Above example will create new sub lists though, alternatively if you could use remove and do:

list_groups = [
    ['john', 'mary', 'peter'],
    ['luh', 'henry', 'maxi'],
    ['patrick', 'juva', 'xavier', 'dorovich']
]
list_users = ['peter', 'henry', 'dorovich']

for group in list_groups:
    for user in group[:]:
        if user in list_users:
            group.remove(user)

print(list_groups)
# [['john', 'mary'], ['luh', 'maxi'], ['patrick', 'juva', 'xavier']]
Thomas
  • 8,357
  • 15
  • 45
  • 81
  • 1
    Thank you so much Thomas! It worked like a charm. I'm new at this automation world and I stuck some times :) I saw the other post, but your answer was way more clearly. – William Andrade Nov 09 '21 at 14:12