- Python Add List to Set with Examples
- 1. Quick Examples of Adding List to Set
- 2. Add List to Set in Python using update()
- 2. Using | Operator to add List to Set
- 3. Using union() Method
- 4. Add List to Set using Looping
- 5. Add Whole List to Set
- Conclusion
- You may also like reading:
- 7 Ways to add all elements of list to set in python
- Frequently Asked:
- Add all elements of a list to set using update() function
- Adding a list to set using add() function
- Add all items in list to set using add() & for loop
- Add a list to set using add() & union()
- Add all elements in a list to set using | operator
- Add a list to set using |= and unpacking list to set
- Adding all elements from multiple lists to the set
- Related posts:
- Как добавить список во множество в Python
- Добавление списка в множество с помощью метода set.update()
- Синтаксис
- Аргумент
- Пример
- Использование функции add() и цикла for
Python Add List to Set with Examples
How to add a list to set in Python? To add elements from the list to the set you can use the update(), union, and add() with for loop. And to add the whole list as a single element to the set you need to convert the list to the set and add it by using add().
- Use update() to add elements from the list to set in-place
- Use | or union() to add elements to the set. This returns a new set with updated elements
- Use for loop with add() to update elements to set iteratively.
- To add the whole list as a single element to set use the add(). To use this you need to convert a list to a tuple.
1. Quick Examples of Adding List to Set
Following are quick examples of adding elements from a list to a set.
# Quick examples of adding list to set # Add list to set myset.update(mylist) # Add list to set using | operator myset = myset | set(mylist) # Add list to set using union() myset = myset.union(mylist) # Add list to set using looping for item in mylist: myset.add(item) # Add whole list to set myset.add(tuple(mylist)) print("Updated Set: ",myset)
2. Add List to Set in Python using update()
To add a list to a set in Python you can use the update() method from the set, this method takes the list as an argument and adds the elements from the list to the set. This method applies that operation in place meaning it adds the elements from the list to the original set.
Note that the set contains only unique elements, so only items that were not present in the set will be added to the set and duplicate items will not be added.
# Consider set & list myset= mylist=[6,7,8] print("Set: ",myset) print("List: ",mylist) # Add list to set myset.update(mylist) print("Updated Set: ",myset)
This example yields the below output.
2. Using | Operator to add List to Set
The | performs a union operation between pairs of objects in Python, you can use this to add elements of a list to a set. Here the | operator implements the set union operation.
# Consider set & list myset= mylist=[6,7,8] print("Set: ",myset) print("List: ",mylist) # Add list to set myset = myset | set(mylist) print("Updates Set: ",myset)
This example also yields the same output. You can also write the union operator as below short form. Here, |= performs an in-place operation between pairs of objects.
# Add list to set myset |= set(mylist)
3. Using union() Method
Alternatively, you can also use the union() method. This method takes the list as an argument and returns the set after adding elements to it. Note that this doesn’t update the existing list instead it returns a new list. To update on the existing list, just assign the result back to the existing set variable.
# Consider set & list myset= mylist=[6,7,8] print("Set: ",myset) print("List: ",mylist) # Add list to set using union() myset = myset.union(mylist) print("Updates Set: ",myset)
This yields the same output as above.
4. Add List to Set using Looping
Loop through the python list and get the element for each iteration and add the element to the set using add() method. Here, the add() method updates the set with the new value from the iteration.
# Consider set & list myset= mylist=[6,7,8] print("Set: ",myset) print("List: ",mylist) # Add list to set using looping for item in mylist: myset.add(item) print("Updates Set: ",myset)
5. Add Whole List to Set
The above examples add each element from the list into a set however, if you wanted to add the whole list as a single element to the set it is not possible as lists are mutable and are not hashable. You need to convert the list to a tuple first before adding to set.
# Consider set & list myset= mylist=[6,7,8] print("Set: ",myset) print("List: ",mylist) # Add whole list to set myset.add(tuple(mylist)) print("Updated Set: ",myset)
This example yields the below output.
Conclusion
In this article, you have learned how to add elements from a list to a set in Python. Use update() to add elements from the list to set in place. Use | or union() to add elements to the set, this returns a new set with updated elements. Use for loop with add() to update elements to set iteratively. To add the whole list as a single element to set use the add(). To use this you need to convert a list to a tuple.
You may also like reading:
7 Ways to add all elements of list to set in python
In this article we will discuss 7 different ways to add all elements of a list to the set in python.
Suppose we have a list and a set i.e.
# Set of numbers sample_set = # List of numbers list_of_num = [10, 11, 12, 13, 14, 15, 16]
Now we want to add all the elements of the list to the set. As set contains only unique elements, so after adding elements from a list to the set, the contents of set should be like,
There are different ways to do this and we will discuss them one by one,
Frequently Asked:
Add all elements of a list to set using update() function
In python, the set class provides a member function update() i.e.
It accepts a single or multiple iterable sequences as arguments and adds all the elements in these sequences to the set.
We can use this update() function to add all elements from a list to the set i.e.
# Create and intialize a set sample_set = # a list of numbers list_of_num = [10, 11, 12, 13, 14, 15, 16] # add all elements in list to the set sample_set.update(list_of_num) print('Modified Set: ') print(sample_set)
We passed a list as an argument to the update() function. It added all the items in the list to the set. The set contains only unique elements, so items which were not present in the set got added and duplicate items were just skipped.
Adding a list to set using add() function
In python, the set class provides a member function add() i.e.
It accepts a single element as an argument and adds that element to the set. But that element should be immutable.
If we try to pass a list to the add() function, then it will give error because list is a mutable object,
TypeError: unhashable type: 'list'
So to add all items in a list to the set using add() function, we need to use a for loop.
Add all items in list to set using add() & for loop
Iterate over all the items in the list using a for loop and pass each item as an argument to the add() function. If that item is not already present in the set,
then it will be added to the set i.e.
# A set of numbers sample_set = # a list of numbers list_of_num = [10, 11, 12, 13, 14, 15, 16] # Iterate over all elements of list and for elem in list_of_num: # add each element to the set sample_set.add(elem) print('Modified Set: ') print(sample_set)
Add a list to set using add() & union()
In python, set class provides a function to add the contents of two sets i.e.
It returns a new set with elements from both s and t.
We can use this to add all elements of a list to the set i.e.
sample_set = list_of_num = [10, 11, 12, 13, 14, 15, 16] # convert list to set and get union of both the sets sample_set = sample_set.union(set(list_of_num)) print('Modified Set: ') print(sample_set)
We converted our list to the set and passed it to the union() function as an argument. union() function returns a set that contains items from both the set i.e. our set and the list (which we converted to the set). As a set contains only unique elements, therefore duplicate elements were just ignored.
Add all elements in a list to set using | operator
We can take union of two sets using | operator too. So, just like the previous solution, we will convert our list to a set and then create a union of both the sets
using | operator i.e.
sample_set = list_of_num = [10, 11, 12, 13, 14, 15, 16] # convert list to set and get union of both the sets using | sample_set |= set(list_of_num) print('Modified Set: ') print(sample_set)
Add a list to set using |= and unpacking list to set
Just like the previous solution, we will take a union of two sets. But to convert our list to a set, we will use string literal and unpack our lists elements inside it,
sample_set = list_of_num = [10, 11, 12, 13, 14, 15, 16] # unpack list to a set and OR that with original set sample_set |= print('Modified Set: ') print(sample_set)
It added all the items in our list to the set. Now our set contains elements from both the original set and list. Duplicate elements were just skipped.
Adding all elements from multiple lists to the set
Suppose we have 3 different lists,
# 3 lists of numbers list_num_1 = [15, 16, 17] list_num_2 = [18, 19] list_num_3 = [30, 31, 19, 17]
Now to add all from these lists to the set, we can use update() function,
# A set of numbers sample_set = # Add multiple lists sample_set.update(list_num_1, list_num_2, list_num_3) print('Modified Set: ') print(sample_set)
In update() function, we can pass multiple iterable sequences as arguments and it adds all the items in these sequences to the set. So, here we passed three lists to the update() function and it added all the elements in these lists to the set.
The complete example is as follows,
def main(): print('*** Add all elements of list to set using update() function ***') # Create and intialize a set sample_set = # a list of numbers list_of_num = [10, 11, 12, 13, 14, 15, 16] # add all elements in list to the set sample_set.update(list_of_num) print('Modified Set: ') print(sample_set) print('*** Adding a list to set using add() function ***') sample_set = # a list of numbers list_of_num = [10, 11, 12, 13, 14, 15, 16] # Wrong Way # Error: TypeError: unhashable type: 'list' # sample_set.add(list_of_num) print('Add all items in list to set using add() & for loop') # A set of numbers sample_set = # a list of numbers list_of_num = [10, 11, 12, 13, 14, 15, 16] # Iterate over all elements of list and for elem in list_of_num: # add each element to the set sample_set.add(elem) print('Modified Set: ') print(sample_set) print('** Add a list to set using add() & union() **') # A set of numbers sample_set = # a list of numbers list_of_num = [10, 11, 12, 13, 14, 15, 16] # convert list to set and get union of both the sets sample_set = sample_set.union(set(list_of_num)) print('Modified Set: ') print(sample_set) print('** Add all elements in a list to set using | operator **') # A set of numbers sample_set = # a list of numbers list_of_num = [10, 11, 12, 13, 14, 15, 16] # convert list to set and get union of both the sets using | sample_set |= set(list_of_num) print('Modified Set: ') print(sample_set) print('** Add a list to set using |= and unpacking list to set **') sample_set = list_of_num = [10, 11, 12, 13, 14, 15, 16] # unpack list to a set and OR that with original set sample_set |= print('Modified Set: ') print(sample_set) print('*** Adding elements from multiple lists to the set ***') # A set of numbers sample_set = # 3 lists of numbers list_num_1 = [15, 16, 17] list_num_2 = [18, 19] list_num_3 = [30, 31, 19, 17] # Add multiple lists sample_set.update(list_num_1, list_num_2, list_num_3) print('Modified Set: ') print(sample_set) if __name__ == '__main__': main()
*** Add all elements of list to set using update() function *** Modified Set: *** Adding a list to set using add() function *** Add all items in list to set using add() & for loop Modified Set: ** Add a list to set using add() & union() ** Modified Set: ** Add all elements in a list to set using | operator ** Modified Set: ** Add a list to set using |= and unpacking list to set ** Modified Set: *** Adding elements from multiple lists to the set *** Modified Set:
Related posts:
Как добавить список во множество в Python
Набор Python используется для сохранения нескольких элементов в одной переменной. Набор не содержит повторяющихся элементов. Итак, если вы хотите хранить уникальные элементы, используйте заданную структуру данных. В набор можно добавить один или несколько элементов. Давайте посмотрим, как добавить список в набор Python.
Добавление списка в множество с помощью метода set.update()
Чтобы добавить список в множество, используйте функцию set.update(). set.update() — это встроенная функция Python, которая принимает один элемент или несколько итерируемых последовательностей в качестве аргументов и добавляет их в набор.
Синтаксис
Аргумент
Метод update() принимает в качестве аргумента element или sequence .
Пример
Давайте определим набор и добавим этот набор в список.
В этом примере мы передали список в качестве аргумента функции update(), и она добавила все элементы списка во множество. Следует помнить, что набор содержит уникальные элементы. Поэтому, если он находит повторяющийся элемент, он удаляет дубликаты из набора.
Таким образом, элементы, которых не было в наборе, были добавлены, а повторяющиеся элементы просто пропущены.
Использование функции add() и цикла for
set.add() — это встроенная функция, которая принимает один элемент в качестве аргумента и добавляет этот элемент в набор. Если вы передадите список или другие итерации, произойдет сбой.