3 Proven Ways to Convert List to Set in Python

In this article, we will explore the list and set and conversion from the list to set in python. Before jumping to this exciting thing, first of all, let’s have an overview of the concept of lists and set.

What is List in python?

List in python is defined as the ordered collection values of different data types inside a square bracket [].

What is List in python
List in python

From the above image, we can have an overview of the list. Here, 0,1 and 2 are the index. Alia, Meera, and Arya are the values or elements of the list having ‘string’ data type.
But the list can be Li = [0, ‘Suman’, 0.24, True]. The length of this list will be 4, having the following indexes: – Li [0] = 0, Li [1] = ‘Suman’, Li [2] = 0.24, Li [3] = True.

What is a set in python?

Set in python is defined as the unordered collection of unique items having different data types inside a curly bracket {}. For example, Se = {1, ‘Mandeep’, True} or may be Se = {‘Sheetal’, ‘Karun’}.

set in python
Sets in python

Difference between list and set

You may be wondering if both list and set can hold items having different data types than what is the difference between them?

ListSet
The list is an Ordered Collection of elements.Set is an Unordered Collection of elements.
Elements of the list can be modified and replaced.Elements in a set cannot be altered, modified, or replaced.

Till now you have understood the concepts of list and set. But the question is why do we need this conversion from the list to set?
The answer is that set does not allow duplicate elements. If we use a set then the elements will be unique.

Why do we need to remove duplicate elements?

we need to remove duplicate elements because there are many instances when we don’t need duplicate values. Well, let me explain this with the help of an example. In real life whenever a user makes an entry into the database, there are high chances that he might commit a mistake while entering data. Suppose a teacher is entering the marks of students into an excel sheet, he ended up entering a student name along with the marks and roll number twice into the excel sheet. So, practically we need to write some code to not let that happen. Hence, we can convert a list into a set.

List to set conversion

You have understood why we need to convert List to Set. Now let’s explore how to convert the list to a set. There are many approaches to doing this.

1. Using set() Function

This approach is one of the simplest methods of converting a list into a set. All you need is to use the set() constructor and pass the list as an argument.

Syntax: set(list).
#create a list
my_list = ['Rice', 'Potato', 'Tomato']

#convert the list using set
se = set(my_list)

#display the set
print(se)

Explanation of the code

  1. Created a list having few elements.
  2. Converted the list to a set using set data structure by passing the list as a parameter.
  3. Displayed the items in the set.

2. Using Custom Function

This approach is using a function call in python.

def list_to_set_conversion(list1):
    se = set()
    for x in list1:
        se.add(x)
    return se
Names = ['Alia', 'Bob', 'Ana', 'Sita', 'Alia']
s = list_to_set_conversion (Names)
print(s)
OUTPUT: {'Ana', 'Alia', 'Bob', 'Sita'}

3. Using dict.fromkeys()

The disadvantage of the above two approaches was that we were not getting the set in an orderly manner. So, for this, we are using our next approach to preserve the order.

list1 = ['Alia', 'Bobby', 'Bobby', 1, 1, 2, 3]
x = list(dict.fromkeys(list1))
se = set(x)
print(se)
Using dict.fromkeys()
dict.fromkeys()

Time Complexity of Converting List into a Set

Every algorithm and every code in this world has a certain space and time complexity. The time complexity of converting a list to a set is linear i.e., the number of elements present in the list. So, if the set has ‘n’ elements, the time complexity is O(n). The reason behind this is that the loop will iterate over each element present in the list that is O(n), and add this element to the set will cost O(1). Together the time complexity will be formulated as O(n) * O(1) = O(n).

Also See

Conclusion

As we all know python is a very simple language to understand because of its simplicity. Due to this the conversion of the python list becomes simpler and easier to read. It’s even simple to understand at what cost we can convert through the time complexity. The time complexity is O(n) which is minimal.

Summary

  1. List in python is ordered collection values.
  2. It can have any type of data.
  3. List is mutable.
  4. It can have duplicate elements.
  5. The element of the list can be accessed by its index.
  6. Sets are an unordered collection of elements.
  7. Sets are immutable.
  8. It cannot have duplicate elements.
  9. Set has a highly optimized method for checking whether an element is contained in the list.
  10. Set is based on the Hash table data structure.
  11. Elements in sets cannot be accessed by its index.
  12. A set() method is used to convert the list into a set by simply passing the list as the parameter.
  13. The time complexity for the conversion is O(n) using a loop.

QNA

Let’s go through some questions to make our learning fun and interactive. We can add a small exercise after every topic so that learners can perform them to gain their confidence.

  1. Predict the output of the code?
def list_to_set_conversion(list1):
   se = set()
    for x in list1:
se.add(x)
    return se
Names = ['Tina', 'Kimmi', 'Chanda', 'Sita', 'Alia', 'Chanda', 'Tina']
s = list_to_set_conversion (Names)
print(s)

Ans: –

0
Please leave a feedback on thisx

2. Complete the missing part of the code so that it displays the following as the correct output.

{‘Abhishek’, ‘Ramesh’, ‘Mohan’, ‘John’, ‘Riya’}

names = ['Mohan', 'Abhishek', 'Ramesh', 'Mohan', 'John', 'Riya']
s =?
print(s)

Ans:-

0
Please leave a feedback on thisx

3.Find the length of the given code snippet.

names = ['Mohan', 'Abhishek', 'Ramesh', 'Mohan', 'John', 'Riya', 'John']
print(len(names))

Ans: –

0
Please leave a feedback on thisx

4. What is the time complexity of the following code snippet?

def list_to_set_conversion(list1):
    se = set()
    for x in list1:
        se.add(x)
    return se
Names = ['Arunima', 'Bobita', 'Annam', 'Sita', 'Alia', 'Annam', 'Alia']
s = list_to_set_conversion (Names)
print(s)

Ans: –

0
Please leave a feedback on thisx

5. Find the length of the given code snippet.

names = {'Mohan', 'Abhishek', 'Ramesh', 'Mohan', 'John', 'Riya', 'John'}
print(len(names))

Ans: –

0
Please leave a feedback on thisx

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Alistair Windsor
Alistair Windsor
2 years ago

I dont know any way to guarantee O(n) running time here. The issue is that when you pull an element you have to examine the existing set to see if it is already present. Using a hashtable implementation you gave expected lookup O(1) but worst case O(n). That gives you worst case runtime of O(n^2). It is simple to get the worst time down to O(n log n) with say a balanced tree but hash tables will typically be faster.

Pratik Kinage
Admin
2 years ago

I believe adding elements to set is of O(1) complexity (hash sets).

Regards,
Pratik