The Python list() function
list() is a built-in Python function used to convert a sequence into a list.
Lists are the most commonly used mutable sequence type in Python; elements can be added, removed, or modified at any time.list() The function can convert iterables such as tuples, strings, dictionaries, and sets into lists.
Word meaning: list means "list" and is a mutable sequence type in Python.
Basic syntax and parameters
Syntax format
list(iterable)
Parameter Description
- Parameter iterable:
- Type: iterable (tuple, string, dictionary, set, etc.)
- Description: the iterable to convert into a list.
Function description
- Return Value: returns a list.
- Special values: returns an empty list when called without arguments
[]。
Example
Example 1: converting from other sequences
Example
Convert from a tuple to a list
t
=
(
1
,
2
,
3
,
4
,
5
)
lst
=
list
(
t
)
(
lst
)
Output: [1, 2, 3, 4, 5]
Convert from a string
s
=
"hello"
lst
=
list
(
s
)
(
lst
)
Output: ['h', 'e', 'l', 'l', 'o']
Convert from a dictionary (keys only)
d
=
{
"a"
:
1
,
"b"
:
2
,
"c"
:
3
}
lst
=
list
(
d
)
(
lst
)
Output: ['a', 'b', 'c']
Convert from a set
s
=
{
3
,
1
,
2
}
lst
=
list
(
s
)
(
lst
)
Output: [1, 2, 3] (automatically sorted)
Empty list
lst
=
list
(
)
(
lst
)
Output: []
Expected output:
[1, 2, 3, 4, 5]
['h', 'e', 'l', 'l', 'o']
['a', 'b', 'c']
[1, 2, 3]
[]
Code analysis:
- Converting a tuple to a list preserves the element order.
- When converting a string, each character becomes an element of the list.
- Converting a dictionary includes only the keys.
Example 2: common list operations
Example
A list can be modified after it is created
lst
=
list
(
(
1
,
2
,
3
)
)
lst.
append
(
4
)
Adding elements
lst.
insert
(
0
,
0
)
Insert elements
(
lst
)
Output: [0, 1, 2, 3, 4]
List comprehension (a more concise approach)
lst
=
[
x *
2
for
x
in
range
(
5
)
]
(
lst
)
Output: [0, 2, 4, 6, 8]
Copy a list
original
=
[
1
,
2
,
3
]
copy
=
list
(
original
)
(
copy
)
Output: [1, 2, 3]
Expected output:
[0, 1, 2, 3, 4]
[0, 2, 4, 6, 8]
[1, 2, 3]
Lists are mutable, so elements can be added, removed, or modified at any time after creation.
Python3 built-in function