Skip to content

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 this x

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 this x

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 this x

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 this x

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 this x

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
Pratik Kinage
2 years ago
Reply to  Alistair Windsor

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

Regards,
Pratik

wpdiscuz   wpDiscuz

两个鬼故事陈字可以起啥名字茶叶品牌商标起名大全可达鸭进化季姓女孩起名字松花蛋怎么制作翁氏起名2020起名男孩武汉f64养生茶起名工农兵路店铺起名多少画好观音菩萨的图片给姓林的男孩子起名全套是什么意思起名八字名典虎年春节祝福语咨询公司名称起名字婴儿起名公司的魔界复仇隐藏英雄密码平步青云的意思百变大咖秀百度影音兔子起名大全韩乔生语录袁隆平的事迹介绍潘氏起名女孩名拉布拉多起名起什么名字好出云战记零宝宝免费起名测名打分生辰八字分析沾沾自喜的意思宝宝宝宝小名乳名大全起名大全少年生前被连续抽血16次?多部门介入两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”淀粉肠小王子日销售额涨超10倍高中生被打伤下体休学 邯郸通报单亲妈妈陷入热恋 14岁儿子报警何赛飞追着代拍打雅江山火三名扑火人员牺牲系谣言张家界的山上“长”满了韩国人?男孩8年未见母亲被告知被遗忘中国拥有亿元资产的家庭达13.3万户19岁小伙救下5人后溺亡 多方发声315晚会后胖东来又人满为患了张立群任西安交通大学校长“重生之我在北大当嫡校长”男子被猫抓伤后确诊“猫抓病”测试车高速逃费 小米:已补缴周杰伦一审败诉网易网友洛杉矶偶遇贾玲今日春分倪萍分享减重40斤方法七年后宇文玥被薅头发捞上岸许家印被限制高消费萧美琴窜访捷克 外交部回应联合利华开始重组专访95后高颜值猪保姆胖东来员工每周单休无小长假男子被流浪猫绊倒 投喂者赔24万小米汽车超级工厂正式揭幕黑马情侣提车了西双版纳热带植物园回应蜉蝣大爆发当地回应沈阳致3死车祸车主疑毒驾恒大被罚41.75亿到底怎么缴妈妈回应孩子在校撞护栏坠楼外国人感慨凌晨的中国很安全杨倩无缘巴黎奥运校方回应护栏损坏小学生课间坠楼房客欠租失踪 房东直发愁专家建议不必谈骨泥色变王树国卸任西安交大校长 师生送别手机成瘾是影响睡眠质量重要因素国产伟哥去年销售近13亿阿根廷将发行1万与2万面值的纸币兔狲“狲大娘”因病死亡遭遇山火的松茸之乡“开封王婆”爆火:促成四五十对奥巴马现身唐宁街 黑色着装引猜测考生莫言也上北大硕士复试名单了德国打算提及普京时仅用姓名天水麻辣烫把捣辣椒大爷累坏了

两个鬼故事 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化