Creates a list from an iterable
Usage
The list()
function creates a list 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)
There is another way you can create lists based on existing lists. It is called List comprehension.
Syntax
list(iterable)
Parameter | Condition | Description |
iterable | Required | A sequence or a collection |
Examples
list()
with no arguments creates an empty list.
L = list()
print(L)
# Prints []
You can convert any sequence (such as a string, tuple or range) into a list using a list()
method.
# string into list
T = list('abc')
print(T)
# Prints ['a', 'b', 'c']
# tuple into list
L = list((1, 2, 3))
print(L)
# Prints [1, 2, 3]
# sequence into list
L = list(range(0, 4))
print(L)
# Prints [0, 1, 2, 3]
You can even convert any collection (such as a dictionary, set or frozen set) into a list.
# dictionary keys into list
L = list({'name': 'Bob', 'age': 25})
print(L)
# Prints ['age', 'name']
# set into list
L = list({1, 2, 3})
print(L)
# Prints [1, 2, 3]