Back to articles list Articles
10 minutes read

Adding a List to a Set in Python: 5 Things You Must Know

What is a Python set? What is a list in Python, for that matter? This article will give an overview of these two data structures and show how to add list values to a set in Python.

To explain the differences between sets and lists in Python – and to help you understand how to add a list to a set correctly – let’s start with an example of these data structures. Look at the two lines of code below:

pets = ["dog", "cat", "red fish"]
pets = {"dog", "cat", "red fish"}
pets = ("dog", "cat", "red fish")

Have you ever seen these Python data structures? The first one is a list, the second one is a set, and the last one is a tuple. All are used to store collections of data. But how is a set different from a list or a tuple?

What You Must Know Before Adding a List to a Set in Python

1.   What’s the Difference Between Python Sets and Lists?

Data structures in Python are used to order, manage, and store data efficiently. Python has four built-in data structures: lists, sets, tuples, and dictionaries. Data structures contain items (or elements) that have a value. Here is a table summarizing some of the common characteristics of data structures in Python:

Data structureOrderedMutableDuplicates allowed
ListYesYesYes
SetNoNoNo
TupleYesNoYes
DictionaryYes, since Python 3.7YesKey: No
Value: Yes
  • Set items are unordered, which means the items do not have a fixed position in the set and their order can change each time you use it. List items are ordered: the position of each item is always the same.
  • Set items are immutable, which means you cannot modify item values once the set is created. However, you can remove existing items or add new items to the set. List items are mutable, meaning you can change item values.
  • Sets do not allow duplicates: each set item is unique. Lists allow duplicates; the same value can appear multiple times in the same list.
  • We won’t focus on tuples and dictionaries here, but suffice it to say that tuples store ordered, changeable lists of non-unique items and dictionaries store ordered, changeable, unique key-value pairs (e.g. "eyes": "green" is a key-value pair, where the key is "eyes" and the value is "green").

If you want to know more about data structures, I suggest you read the article Python Lists, Tuples, and Sets: What’s the Difference?. If you want to go further with data structures in Python, I highly recommend taking our Python Data Structures in Practice course. It will teach you how to solve fundamental programming problems with basic data structures.

2.  When to Use Each Data Structure

In Python, no data structure is inherently better than another; each data structure has different properties and, therefore, different uses. You should choose the correct data structure according to what you will do. Here are some practical examples of choosing the right data structure:

  • If you want to remove duplicates from a huge data collection, use a set.
  • If you want to store all collection values in an ordered way, use a list.
  • If you want to store all collection values in an ordered way and you know they’ll never change, use a tuple. It will be more efficient in terms of memory.
  • If you want to manage items associated with a unique value (key), use a dictionary.

3.  How to Declare a Set and a List in Python

Declaring a set

There are multiple ways to declare a set in Python. One is by surrounding the values with curly brackets:

# Declares a set with items
pet_set = {"dog", "cat", "red fish"}

You can also use the set() constructor function, which allows you to build a set from another data structure (e.g. a list, tuple, or dictionary). Notice the different types of brackets used to indicate what data structure we’re converting to a set:

# Builds a set from a list
pet_set = set(["dog", "cat", "red fish"])

# Builds a set from a tuple
pet_set = set(("dog", "cat", "red fish")) 

# Builds a set from a dictionary
pet_set = set({"dog": "Rex", "cat": "Mitchi", "red fish": "Bubble"})

Note that you can use the set constructor function with any iterable object, which means an object capable of returning its members one by one. If we try with a string, we will obtain the following result:

# Builds a set from a string
pet_set = set("dog")

# Prints the result
print(pet_set)	# Shows: {"d", "o", "g"}

If you want to declare an empty set, use a set() constructor without anything in the round brackets. Don’t use empty curly brackets; that would make it a dictionary declaration.

# Declares an empty set
pet_set = set()

# Warning: This is an empty dictionary!
pet_dict = {}

Remember that sets do not allow duplicate values; if you declare a set with duplicate values, the set will remove the duplicates:

# Builds a set with duplicate values
pet_set = {"dog", "cat", "cat"}

# Prints the result
print(pet_set)	# Shows: {"dog", "cat"}

Declaring a list

Declaring a list in Python is quite similar – just use square brackets surrounding the values:

# Declares an list with items
pet_list = ["dog", "cat", "red fish"]

You can also use the list() constructor function:

# Builds a list from a set
pet_list = list({"dog", "cat", "red fish"})

# Builds a list from a tuple
pet_list = list(("dog", "cat", "red fish"))

# Builds a list from a dictionary
pet_list = list({"dog": "Rex", "cat": "Mitchi", "red fish": "Bubble"})

You can use the list() constructor with any iterable object. If we use it with a string, we will obtain the following result:

# Builds a list from a string
pet_list = list("dog")

# Prints the result
print(pet_set)	# Shows: ["d", "o", "g"]

If you want to declare an empty list, you use an empty list() constructor or use square brackets with no values.

# Declares an empty list with constructor
pet_list = list()

# Declares an empty list with brackets
pet_list = []

You can also declare and initialize lists in very cool way using the multiplication method:

# Declares a list with items
pet_list = ["dog"] * 3

# Prints the result
print(pet_list)	# Shows: ["dog", "dog", "dog"]

Remember that lists have the ability to store duplicate values:

# Builds a list with duplicate values
pet_list = ["dog", "cat", "cat"]

# Prints the result
print(pet_list)	# Shows: ["dog", "cat", "cat"]

4.  Which Data Types Can I Use in Sets and Lists?

Python's built-in data structures accept any built-in data type, such as string, integer, or boolean. It is possible to build sets and lists made up of one or multiple data types.

Here are some examples of sets using different data types:

# Declares a set with string items
pet_set = {"dog", "cat", "red fish"}

# Declares a set with integer items
pet_set = {1, 532, 165}

# Declares a set with boolean items
pet_set = {True, False}

# Declares a set with string, float, and boolean items
pet_set = {"parrot", 1.5, False}

Note: In a set, the statements 1 == True and 0 == False are true. So if you have both values in a set, the set considers them duplicate values and keeps only one.

# Declares a set with duplicate values of different types
pet_set = {"dog", 1, True}

# Prints the result
print(pet_set)	# Shows: [1, "dog"]

Here are some examples of lists using multiple data types:

# Declares a list with string items
pet_list = ["dog", "cat", "red fish"]

# Declares a list with integer items
pet_list = [1, 532, 165]

# Declares a list with boolean items
pet_list = [True, False, False]

# Declares a list with string, float, and boolean items
pet_list = ["parrot", 1.5, False]

Remember that, unlike sets, lists allow duplicated values, including those with multiple data types.

# Declares a list with duplicated items
pet_list = ["dog", "dog", False, False, 1, 1]

# Prints the result
print(pet_list)	# Shows: ["dog", "dog", False, False, 1, 1]

So, How Can I Add List Values to a Set in Python?

Now that we understand sets and lists in Python, we can answer the question in this article's title: How can I add list values to a set? There are several workarounds to achieve it.

Using set.update()

The set data structure provides some built-in functions. One of them is the update() function. This function can be used with any iterable object; therefore, it will work with a list:

# Declares a set with items
pet_set = {"dog", "cat", "red fish"}

# Declares a list with items
pet_list = ["gecko", "parrot"]

# Calls the update() function with the list
pet_set.update(pet_list)

# Prints the result
print(pet_set)	# Shows: {'dog', 'parrot', 'cat', 'gecko', 'red fish'}

Using set.add()

Another built-in function provided by the set data structure is the add() function. As you might guess, it allows us to add one or more items to a set. To add all values of a list to a set, we should loop the list and add each item.

# Declares a set with items
pet_set = {"dog", "cat", "red fish"}

# Declares a list with items
pet_list = ["dog", "gecko", "parrot"]

# Loops the list and add each item to the set
for item in pet_list:
	pet_set.add(item)

# Prints the result
# Note that the "dog" duplicate value has been removed from the set
print(pet_set)	# Shows: {'dog', 'parrot', 'cat', 'gecko', 'red fish'}

Using set.union()

The union() built-in function combines the elements of two sets. So to add list values to a set, we need first to convert the list into a set and then use union():

# Declares a set with items
pet_set = {"dog", "cat", "red fish"}

# Declares a list with items
pet_list = ["gecko", "parrot"]

# Transforms the list into a set
pet_set_2 = set(pet_list)

# Performs a combination of sets using the union() function 
pet_set = pet_set.union(pet_set_2)

# Prints the result
print(pet_set)	# Shows: {'dog', 'parrot', 'cat', 'gecko', 'red fish'}

Using the OR | operator

According to Python’s documentation, an elegant alternative to the union() function is using the OR operator | to concatenate two sets:

# Declares a set with items
pet_set = {"dog", "cat", "red fish"}

# Declares a list with items
pet_list = ["gecko", "parrot"]

# Transform the list into a set
pet_set_2 = set(pet_list)

# Performs a combination of sets using the OR | operator 
pet_set = pet_set | pet_set_2 

# Prints the result
print(pet_set)	# Shows: {'dog', 'parrot', 'cat', 'gecko', 'red fish'}

Note that you can use the shorter |= operator to do the same thing:

pet_set |= set(pet_list)

As you probably have figured out, these two options work exactly the same as using union() and produce the same result.

If you want to go further with set operations, I recommend the article Python Set Operations: Union, Intersection, and Difference.

Adding List Values to a Set in Python: Easy Peasy!

In this article, we reviewed Python’s list and set data structures. We learned how to declare them and what kind of data types they can work with. Then we finally answered the main question of this article by showing various ways to add list values to a set.

Don’t be afraid to try new things in Python! Python is a very flexible language from a conceptual and syntactical point of view; it lets you find simple and understandable workarounds for a given problem.

Did this article motivate you to learn more about Python? In that case, check out our Learn Programming with Python to get started!