Python append list if not exists
7 years later, allow me to give a one-liner solution by building on a previous answer. You could do the followwing:
to Add
This results in Explanation: Now let me explain what happens, starting from the inside of the This, I believe, will work for all types of data in a list, and objects as well if done correctly. Append value to list if not already present using Python #To append a value to a list if not already present:
We used the The in operator tests for membership. For example,
If the value is not present in the list, we use the The list.append() method adds an item to the end of the list. The method returns You can use the same approach if you need to iterate over a collection of values, check if each value is present in a list and only append values that are not present.
We used a On each iteration, we check if the current value is present in the other list. If the value is not present in the list, we use the The An alternative approach to consider is to use a
Set objects are an unordered collection of unique elements.
We used the However, you should only use this approach if the order of the elements is not important because If you decide to use a You can directly use the
|