Home > Software engineering >  Check if an element is already in a list
Check if an element is already in a list

Time:10-14

I have a list 1 with some elements. Then I ask the user to add some elements to the list. This I do by creating a new list: list_added. I want to add the list_added to the original list (using list.extend(list_added)). But before I do that. I want to check if an element that I've added is already in the original list. And if so the lists shall not be added together.

So if list = ["A", "B", "C", "D"] and list_added = ["D", "H"]

then I dont want the lists to add. How could I do this?

CodePudding user response:

One way I'd do it is to use an unordered set, which assumes that ordering of elements in the collection doesn't matter.

Below is an example that shows two ways to add elements to a set - either extending the set with an existing list, or adding elements one at a time.

my_list = ["A", "B", "C", "D"]
my_set = set(my_list)

list_added = ["D", "H"]

# update with new elements
my_set.update(list_added)

# no duplicates
print(my_set)
# {'A', 'H', 'C', 'D', 'B'}

# reset the set elements
my_set = set(my_list)

for elem in list_added:
    my_set.add(elem)

print(my_set)
# {'A', 'H', 'C', 'D', 'B'}
  • Related