Python list() Function
Last Updated :
29 Nov, 2023
Python list() function takes any iterable as a parameter and returns a list. In Python iterable is the object you can iterate over. Some examples of iterables are tuples, strings, and lists.
Python list() Function Syntax
Syntax: list(iterable)
Parameter:
- iterable: an object that could be a sequence (string, tuples) or collection (set, dictionary) or any iterator object.
Note: If we don’t pass any parameter then the list() function will return a list with zero elements (empty list).
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
string = "ABCDEF"
list1 = list (string)
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
tuple1 = ( 'A' , 'B' , 'C' , 'D' , 'E' )
list1 = list (tuple1)
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
set1 = { 'A' , 'B' , 'C' , 'D' , 'E' }
dictionary = { 'A' : 1 , 'B' : 2 , 'C' : 3 , 'D' : 4 , 'E' : 5 }
list1 = list (set1)
list2 = list (dictionary)
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
list1 = list ( input ( "Please Enter List Elements: " ))
print (list1)
|
Output
Please Enter List Elements: 12345
['1', '2', '3', '4', '5']
Share your thoughts in the comments
Please Login to comment...