Sets and lists are used in Python to store and manipulate data in a program. This article discusses list vs set in Python to compare their performance, syntax, mutability, and repetition.
Python List vs Set Summary Table
The following table contains a summary of the differences between a Python list and a set.
List | Set |
A list can contain duplicate elements. | A set contains unique elements. |
We can access an element from a list using subscript notation. | We cannot access elements in a set using subscript notation. |
A list can contain different data types and other container objects such as a list, tuple, set, or dictionary. | A set can contain only contain immutable objects such as integers, strings, tuples, and floating-point numbers. |
We can create nested lists in Python. | We cannot create nested sets in Python. |
Lists allow random access to elements. | Sets do not allow random access to elements. |
A Python list contains elements in an ordered sequence. | Sets contain elements in an unordered manner. |
Now, let us discuss all the differences in detail with code examples.
What is a Python List?
A Python list is a data structure that stores elements in sequential order. We can define a list in Python using square brackets as shown below.
myList=[1,2,3,4,5,6]
print("The list is:")
print(myList)
Output:
The list is:
[1, 2, 3, 4, 5, 6]
We can also convert another container object like a tuple to a list using the list()
function. The list()
function takes another element as its input argument and returns a new list containing all the elements of the input container object. You can observe this in the following example.
myList=list((1,2,3,4,5,6))
print("The list is:")
print(myList)
Output:
The list is:
[1, 2, 3, 4, 5, 6]
A list can contain objects of different data types and other container objects like lists, tuples, sets, etc. as shown below.
myList=[1,"PFB",(1,2,3),101.1117,5,6]
print("The list is:")
print(myList)
Output:
The list is:
[1, 'PFB', (1, 2, 3), 101.1117, 5, 6]
You can observe that the list in the above list contains an integer, a string, a tuple, and a floating point number.
All the elements in a list are in a particular order and we can access them using the Python indexing operator. The first element in the list has an index 0, the second element has an index 1, and so on. You can observe this in the following example.
myList=[1,"PFB",(1,2,3),101.1117,5,6]
print("The list is:")
print(myList)
print("The element at index 3 is:")
print(myList[3])
Output:
The list is:
[1, 'PFB', (1, 2, 3), 101.1117, 5, 6]
The element at index 3 is:
101.1117
We can also use negative indices to access the elements in a list. A negative index -1 gives us the last element of the list. Index -2 gives the second last element, and so on. You can observe this in the following example.
myList=[1,"PFB",(1,2,3),101.1117,5,6]
print("The list is:")
print(myList)
print("The element at index -2 is:")
print(myList[-2])
Output:
The list is:
[1, 'PFB', (1, 2, 3), 101.1117, 5, 6]
The element at index -2 is:
5
What is a Python Set?
A Python set is a data structure used to store unique elements in an unordered manner. We can define a set in Python using curly braces as shown below.
mySet={1,2,3,4,5,6}
print("The set is:")
print(mySet)
Output:
The set is:
{1, 2, 3, 4, 5, 6}
We can also convert another container object like a list to a set using the set()
function. The set()
function takes another container object as its input argument and returns a set. You can observe this in the following example.
mySet=set([1,2,3,4,5,6])
print("The set is:")
print(mySet)
Output:
The set is:
{1, 2, 3, 4, 5, 6}
Elements in a set are in no particular order. You cannot access them using indices. However, you can iterate through the elements in a set using a for loop as shown below.
mySet=set([1,2,3,4,5,6])
print("The set is:")
print(mySet)
print("The elements in the set are:")
for element in mySet:
print(element)
Output:
The set is:
{1, 2, 3, 4, 5, 6}
The elements in the set are:
1
2
3
4
5
6
Python List vs Set: Syntax
There are many differences in the syntax of a list and a set.
We can access elements of a list using subscripts. On the contrary, if we try to access an element in a set using subscripts, the program will run into an error. You can observe this in the following example.
myList=[1,2,3,4,5,6]
mySet={1,2,3,4,5,6}
print("The list is:")
print(myList)
print("The element is:",myList[2])
print("The set is:")
print(mySet)
print("The element is:",mySet[2])
Output:
The list is:
[1, 2, 3, 4, 5, 6]
The element is: 3
The set is:
{1, 2, 3, 4, 5, 6}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_22443/2698134410.py in <module>
6 print("The set is:")
7 print(mySet)
----> 8 print("The element is:",mySet[2])
TypeError: 'set' object is not subscriptable
In this example, you can observe that we can access the element in the list using the subscript notation. However, the program runs into a Python TypeError exception when we do so with a set.
We can create an empty list using square brackets [] without any element. However, we cannot create a set using curly braces {} without elements. A set of curly braces without any element creates a dictionary and not a set. You can observe this in the following example.
myList=[]
mySet={}
print("The data type of myList is:")
print(type(myList))
print("The data type of mySet is:")
print(type(mySet))
Output:
The data type of myList is:
<class 'list'>
The data type of mySet is:
<class 'dict'>
In the above example, you can observe that the data type of [] is list whereas that of {} is dict and not set. Hence, we cannot create an empty set using the curly braces.
We can create nested lists in Python. However, we can’t create nested sets in Python. Doing so will lead to error as shown below.
myList=[[1,2,3],[4,5,6],[7,8,9]]
print("The list is:")
print(myList)
mySet={{1,2,3},{4,5,6},{7,8,9}}
print("The set is:")
print(mySet)
Output:
The list is:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_22443/2710306261.py in <module>
2 print("The list is:")
3 print(myList)
----> 4 mySet={{1,2,3},{4,5,6},{7,8,9}}
5 print("The set is:")
6 print(mySet)
TypeError: unhashable type: 'set'
List vs Set: Repetition
Lists allow duplicate elements to be present in them. However, we cannot repeat elements in a set. Even if we pass multiple instances of an element while creating a set, it will store only one instance of a single element. You can observe this in the following example.
myList=[1,2,2,3,3,3,4,4,4,4,5]
print("The list is:")
print(myList)
mySet={1,2,2,3,3,3,4,4,4,4,5}
print("The set is:")
print(mySet)
Output:
The list is:
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5]
The set is:
{1, 2, 3, 4, 5}
In the above example, you can observe that the set contains only unique elements even if we pass duplicate elements while creating the set.
List vs Set: Mutability
Lists and sets both are mutable. You can add and delete elements from a set as well as a list. However, you cannot add mutable objects like lists, sets, dictionaries, etc to a set. Sets can only contain immutable elements.
Python in Operator: List vs Set
We can use the in operator to check if an element is present in a set as well as a list. There is no difference between using the in operator with a list or set. However, the performance of the in operator between a list and a set is huge. A set uses the hash to search for the elements. On the other hand, a list needs to iterate over all the elements to search for an element. Due to this, a set is almost three times faster than a list while using the in operator. You can observe this in the following image.
Python List vs Set: Performance
Creating a set requires extra work compared to creating a List. For each element with which we want to initiate a set, the interpreter needs to check if the element is already present in the set or not. Due to this, creating a list has a better performance compared to creating a set. Creating a set takes more than double the time creating a list with the same number of elements. You can observe this in the following example.
While adding a new element to a set, the program first checks if the element is present in the set or not. If it’s not present, then only the element is added to the set. In a list, the element is directly appended to the list. Due to the overhead of checking the presence of the new element, a set has a bad performance compared to a list while adding a new element. You can observe this in the following example.
Even while iterating over the elements using a for loop, a list has better performance than a set as shown below.
Hence, we can say that a Python list has a better performance than a set in most of the operations if both objects have the same number of elements.
When to Use a List vs Set in Python?
Lists allow duplicate elements and random access. Hence, if you want to store duplicate elements and access elements in a random manner using their position, you should use a list. If you need to store unique elements, you can use a set.
Conclusion
In this article, we discussed list vs set in Python to compare performance, syntax, mutability, and repetition. To learn more about Python programming, you can read this article on list vs dictionary in Python. You might also like this article on if vs elif vs else in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.