Set to list in PythonIn this article, we will discuss how we can convert a set to a list in Python. Before that let’s have a quick revision of lists and sets. List – It is a sequence of elements enclosed in square brackets where each element is separated with a comma. Syntax of a list is- We can print the list and check its type using- NOTE: The list is mutable which means we can change its elements.Set – It is an unordered collection of elements that contains all the unique values enclosed within curly brackets. Syntax of a set is- We can print the set and check its type using- The different approaches of converting a set to a string that we will use are-
Using list()In the first method, we will use list() to convert the set. The following program shows how it can be done- Output: ['C','C++','Java','Python','HTML' ] Explanation: Let us understand what we have done in the above program-
Using sorted()The second approach is to use the sorted() function to convert a set to a list. The program below illustrates the same- Output: ['C','C++','Java','Python','HTML' ] Explanation: Let us understand what we have done in the above program-
Using *setIn the third method, we will use the *set to convert a set to a list in Python. The *set unpacks the set inside a list. The following program shows how it can be done- Explanation: Let us understand what we have done in the above program-
Output ['C','C++','Java','Python','HTML' ] Using for loopIn the fourth method, we will use for loop to convert a set to a list in Python. The program below illustrates the same- Output: ['C','C++','Java','Python','HTML' ] Let us understand what we have done in the above program-
Using frozensetFinally, in the last method, we will use frozenset to convert a set to a list in Python. The difference between a set and a frozenset is that a set is mutable whereas a frozenset is immutable. The following program shows how it can be done- Output: ['C','C++','Java','Python','HTML' ] Explanation: Let us understand what we have done in the above program-
ConclusionIn this tutorial, we came across the different approaches of converting a set to a list in Python. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263397.html