Convert List to Set, Tuple, and Dictionary
In this tutorial, we will convert List to Set, Tuple, and dictionary in Python.
How to Convert List to Set?
We have a list. When we need to convert a list to a set So, there are many ways to convert a list into a set.
We will use a set() method to convert into set.
Example:
List Input - [1,2,3,4,5,6,7,8,9]
Set Output - {1,2,3,4,5,6,7,8,9}
Source Code:
#list to set
L=[1,2,3,4,5,6]
print(L)
S=set(L)
print(S)
Output:
[1,2,3,4,5,6]
{1,2,3,4,5,6}
And When we need to convert set to list then we will use list() function.
#set to list
S={1,2,3,4,5,6}
print(S)
L=list(S)
print(L)
Output:
{1,2,3,4,5,6}
[1,2,3,4,5,6]
How to Convert List to Tuple?
We have a list. When we need to convert a list to a tuple So, there are many ways to convert a list into a tuple.
We will use a tuple() method to convert into tuple.
Example:
List Input - [1,2,3,4,5,6,7,8,9]
Tuple Output - (1,2,3,4,5,6,7,8,9)
Source Code:
#list to tuple
L=[1,2,3,4,5,6]
print(L)
T=tuple(L)
print(T)
Output:
[1,2,3,4,5,6]
(1,2,3,4,5,6)
And When we need to convert a tuple to list then we will use list() function.
#tuple to list
T=(1,2,3,4,5,6)
print(T)
L=list(T)
print(L)
Output:
(1,2,3,4,5,6)
[1,2,3,4,5,6]
How to Convert List to Dictionary?
We have a list. When we need to convert a list to a dictionary So, there are many ways to convert a list into a dictionary.
We will use dict comprehension to convert list to dictionary.
Example:
List Input - [1,'a',2,'b',3,'c']
Dictionary Output - {1:'a',2:'b',3:'c'}
Source Code:
#list to dictionary
L=[1,'a',2,'b',3,'c']
print(L)
D={L[i]: L[i+1] for i in range(0,len(L),2)}
print(D)
Output:
[1,'a',2,'b',3,'c']
{1:'a',2:'b',3:'c'}
And When we need to convert a dictionary to list then we will use list comprehension.
#dictionary to list
D={1:'a',2:'b',3:'c'}
print(D)
L=list(D.items())
print(L)
Output:
{1:'a',2:'b',3:'c'}
[(1,'a'),(2,'b'),(3,'c')]
0 Comments