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.
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).
Lets see some examples for better understanding.
Example 1: Using list() to create a list from a string
Python
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
Python
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
Python
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:
['C', 'E', 'D', 'B', 'A']
['A', 'B', 'C', 'D', 'E']
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
Python
list1 = list ( input ( "Please Enter List Elements: " ))
print (list1)
|
Output:
Please Enter List Elements: 12345
['1', '2', '3', '4', '5']
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!