Add a List to a Set in Python

  • Post category:List

Adding a list to a set is a common operation in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to combine a list with a set efficiently.

Example 1:

fruits = {'apple', 'banana'}
new_fruits = ['kiwi', 'orange']
fruits.update(new_fruits)
print(fruits)

Output: {‘kiwi’, ‘banana’, ‘orange’, ‘apple’}

Example 2:

numbers = {1, 2, 3, 4}
new_numbers = [3, 4, 5, 6]
numbers |= set(new_numbers)
print(numbers)

Output: {1, 2, 3, 4, 5, 6}