Python list() Function
The list()
constructor creates a list object from an iterable.
The iterable may be a sequence (such as a string, tuple or range) or a collection (such as a dictionary, set or frozen set)
Another way to create list that allows to create lists based on existing lists is called List Comprehension.
Syntax
list(iterable)
list() Parameters
Python list()
function parameters:
Parameter | Condition | Description |
---|---|---|
iterable | Optional | A sequence or a collection |
list() Return Value
Python list()
constructor returns a list:
- If no parameters are passed, it returns an empty list
- If iterable is passed as a parameter, it creates a list consisting of iterable's items.
Examples
Example 1: Creating an Empty List
Let's create an empty List using list()
without argument.
empty_list = list()
print(empty_list) # Output: []
output
[]
Example 2: Creating a List from a String
Let's create a List from a String using list()
:
string = "ABCDE"
list1 = list(string)
print(list1) # Output: ['A', 'B', 'C', 'D', 'E']
output
['A', 'B', 'C', 'D', 'E', 'F']
Example 3: Creating a List from a Tuple
Let's create a List from a Tuple using list()
:
tuple1 = ('A', 'B', 'C', 'D', 'E')
list1 = list(tuple1)
print(list1) # Output: ['A', 'B', 'C', 'D', 'E']
output
['A', 'B', 'C', 'D', 'E']
Example 4: Creating a List from a Set
Let's create a List from a Set using list()
:
set1 = {1, 2, 3, 4, 5}
list1 = list(set1)
print(list1) # Output: [1, 2, 3, 4, 5]
output
[1, 2, 3, 4, 5]
The order of the elements in the list may vary because sets are unordered collections!
Example 5: Creating a List from a Dictionary
Let's create a List from a Dictionary using list()
:
dict1 = {'one': 1, 'two': 2, 'three': 3}
list1 = list(dict1)
print(list1) # Output: ['one', 'two', 'three']
output
['one', 'two', 'three']
Example 6: Creating a List from a List
Let's create a List from a List using list()
:
list1 = ['a', 'b', 'c', 'd', 'e']
new_list = list(list1)
print(new_list) # Output: ['a', 'b', 'c', 'd', 'e']
output
['a', 'b', 'c', 'd', 'e']
Example 7: Creating a List from a Range
Let's create a List from a Range using list()
:
list1 = list(range(0, 5))
print(list1) # Output: [0, 1, 2, 3, 4]
output
[0, 1, 2, 3, 4]