Converting list to set in python

5 ways to convert List to Set in Python

In this post, we are going to understand 5 ways to convert List to Set in Python with code examples. We will explore very simple ways to convert Python List to set.

1. Set constructor to convert List to Set

To convert a LIST into a SET we can use inbuilt the set() constructor. We pass a list as an argument to set the constructor.

The main difference between SET and List is that set is an unordered, unique collection that does not allow duplicate. So while converting the List to SET all the duplicate items of the list will be removed. This is an easy method to convert List to Set

Читайте также:  Редактор кода html от google

Program Example

list_num =[12,15,12,20,25,25,15] print(f'original List:\n\n') myset = set(list_num) print(f'result set :\n')

original List: [12, 15, 12, 20, 25, 25, 15] result set :

2.Convert List of string to Set

In this example, we are converting a List of strings to SET. As you can see from the output, all the duplicate has been removed.

original list: [‘dog’, ‘cat’, ‘mouse’, ‘snake’, ‘fox’, ‘tiger’, ‘lion’] set from list:

3. Convert a List of mixed dataype to Set

In this example, we are performing operation a List of mixed datatype to SET. As you can see output all the duplicates have been removed while converting.

Program Example

list_orignal =[12,15,12,20,25,25,15,'at','at','on',23.5,20.4,23.5] print(f'original List:\n\n') list_to_set = set(list_orignal) print(f'List to Set :\n')

original List: [12, 15, 12, 20, 25, 25, 15, ‘at’, ‘at’, ‘on’, 23.5, 20.4, 23.5] List to Set :

4.Convert List to Set Preserve order

The simple ways to convert a list to set by Preserve order. The steps are here:

  • convert list to the dictionary using dict.fromkeys() method that removes all duplicates and dictionary to list
  • Convert dictionary to list using list() constructor.

Program Example

list_animal =['dog','cat','cat','snake',13,14,15] list_to_dict = dict.fromkeys(list_animal) print('list to dict:\n',list_to_dict) result_list = list(list_to_dict) print('\n',result_list)
list to dict: ['dog', 'cat', 'snake', 13, 14, 15]

5. Convert lists of list to Set

We have defined a custom function lists_to_Set to convert a list of lists to Set.

Program Example

result_list = [] def lists_to_Set(lists_to_set): for val in lists_to_set: if type(val) == list: lists_to_Set(val) else: result.append(val) return set(result_list) lists_to_set = [[10, 17,17], [17, 15, 34, 34], [12,16,89,90]] print(lists_to_Set(lists_to_set))

Summary

In this post we have learned How to convert List to Set in Python with code example.

Источник

How to convert list to set Python (4 Easy Ways)

convert list to set python

In this article, we will solve a problem statement of how to convert List to Set Python. We will be discussing the steps and python methods required to solve this problem and also the time complexity of the methods used to convert list to set in python.

Understanding the Problem Statement

Before jumping directly into the python program let’s know about the background of the problem statement, python list, and python set.

What is List in Python? The list is one of the 4 built-in data types in Python used to store data that is mutable, can be ordered, and can be duplicated within the list. The list is created by placing all the elements within the square brackets and separated by commas.

Example : list1 = [1,2,3,'john',7.5,3]

What is Set in Python? Like list, Set is also one of the 4 built-in data types in Python used to store data but cannot have duplicate elements and cannot be modified. The Set is created by placing all the elements within the curly brackets separated by commas.

Since now we know that set contains only distinct elements, hence when we create a set from a list we will get all distinct elements of a list in the set.

Difference between List and Set in Python

The list allows duplicate elements

The list is an ordered sequence

The elements in the list are present in square brackets [ ].

Using the list we can implement ArrayList, LinkedList, Vector, Stack

How to Convert list to set Python

  1. Using set() method
  2. Using For loop and set.add() method
  3. Using set comprehension
  4. Using dict.fromkey() method

All the above ways are discussed below in detail.

Method 1- Using set()

The best way to convert list to set in Python is by using the set() function. The set() method is used to convert an iterable element such as a list, dictionary, or tuple into the set.

Python Code:

# sample_list is defined list sample_list = [1,2,3,'seeker',3,7.5] # set() to convert list to set sample_set = set(sample_list) print(sample_set) #printing set

Method 2- For Loop and set add() method

In this method, we use for loop to access each element of a list and add that element in a set by using add() function.

Python Code

# sample_list is defined list sample_list = [1,2,3,'seeker',3,7.5] # set() to convert list to set sample_set = set() # defining set #using for loop for i in sample_list: #adding i to b sample_set.add(i) print(sample_set)

Method 3- Using Set Comprehension

In this method, we will be using set comprehension. You can know about set comprehension from here.

Python Code

# a is defined list a = [1,2,3,'seeker',3,7.5] t = # set comprehension print(t)

Method 4- Using dict.fromkey()

In this method, we will be using the dictionary fromkeys() method. To know about dict.fromkey() method you can visit here.
The only disadvantage of this method is we don’t get set in an orderly manner.

Python Code

# a is defined list a = [1,2,3,'seeker',3,7.5] # Using dict.fromkeys() method x = list(dict.fromkeys(a)) converted_set = set(x) print(converted_set)

Time Complexity to convert list to set in Python?

The time complexity to convert list to set is Big O(N), where N is the number of elements present in the list, i.e it is linear to the elements present in the list. This is because the complexity of set operations to add/delete an element is O(1). Hence while converting a list of N elements into a set, we require such N operations, which will have the complexity of N * O(1) i.e O(N * 1) = O(N).

Above, we have discussed 4 methods that can help you to convert list to set in python. But which method is best from above with respect to time so that you can practice using that method in upcoming projects or problems.

From the above table, we can see that using the set() function method takes less time compared to other methods.

Conclusion

Hence we can convert list to set Python by using set() method, for loop, and set comprehension. The Time complexity for converting the list to set is O(N). We can also conclude the best way to convert list to set is by using the set() method.

I am Passionate Computer Engineer. Writing articles about programming problems and concepts allows me to follow my passion for programming and helping others.

Источник

3 Proven Ways to Convert List to Set in Python

convert list to set 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

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 = or may be Se = .

set 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?

List Set
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)

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()

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.

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)

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

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

3.Find the length of the given code snippet.

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

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)

5. Find the length of the given code snippet.

Источник

Оцените статью