list() Function in Python
We can create a Python list by using list() function. Below are the ways by which we can use list() function in Python:
- To create a list from a string
- To create a list from a tuple
- To create a list from set and dictionary
- Taking user input as a list
Example 1: Using list() to Create a List from a String
In this example, we are using list() function to create a Python list from a string.
Python3
# initializing a string string = "ABCDEF" # using list() function to create a list list1 = list (string) # printing list1 print (list1) |
Output
['A', 'B', 'C', 'D', 'E', 'F']
Example 2: Using list() to Create a List from a Tuple
In this example, we are using list() function to create a Python list from a Tuple.
Python3
# initializing a tuple tuple1 = ( 'A' , 'B' , 'C' , 'D' , 'E' ) # using list() function to create a list list1 = list (tuple1) # printing list1 print (list1) |
Output
['A', 'B', 'C', 'D', 'E']
Example 3: Using list() to Create a List from Set and Dictionary
In this example, we are using list() function to create a Python list from set and dictionary.
Python3
# initializing a set set1 = { 'A' , 'B' , 'C' , 'D' , 'E' } # initializing a dictionary dictionary = { 'A' : 1 , 'B' : 2 , 'C' : 3 , 'D' : 4 , 'E' : 5 } # using list() to create a list list1 = list (set1) list2 = list (dictionary) # printing print (list1) print (list2) |
Output
['A', 'C', 'B', 'E', 'D'] ['A', 'C', 'B', 'E', 'D']
We can also use list() function while taking input from user to directly take input in form of a list.
Example 4: Taking User Input as a List
In this example, we are using list() function to take user input from the user and create a Python list from that input.
Python3
# Taking input from user as list list1 = list ( input ( "Please Enter List Elements: " )) # printing print (list1) |
Output
Please Enter List Elements: 12345
['1', '2', '3', '4', '5']