Python list() Function

Python3 内置函数Python3 Built-in Functions


list()It is a built-in function in Python used to convert a sequence into a list.

Lists are the most commonly used mutable sequence type in Python, allowing elements to be added, removed, or modified at any time.list()The function can convert iterable objects such as tuples, strings, dictionaries, and sets into lists.

Word Meaning: listIt means "list" and is a mutable sequence type in Python.


Basic Syntax and Parameters

Syntax Format

list(iterable)

Parameter Description

  • Parameter iterable:
    • Type: iterable object (tuple, string, dictionary, set, etc.)
    • Description: The iterable object to convert to a list.

Function Description

  • Return Value: Returns a list.
  • Special Value: Returns an empty list when called without parameters[]。

Examples

Example 1: Converting from Other Sequences

Examples

# Convert from tuple to list
t = (1, 2, 3, 4, 5)
lst = list(t)
print(lst)        # Output: [1, 2, 3, 4, 5]

# Convert from string
s = "hello"
lst = list(s)
print(lst)        # Output: ['h', 'e', 'l', 'l', 'o']

# Convert from dictionary (keys only)
d = {"a": 1, "b": 2, "c": 3}
lst = list(d)
print(lst)        # Output: ['a', 'b', 'c']

# Convert from set
s = {3, 1, 2}
lst = list(s)
print(lst)        # Output: [1, 2, 3] (auto-sorted)

# Empty list
lst = list()
print(lst)        # Output: []

Expected output:

[1, 2, 3, 4, 5]
['h', 'e', 'l', 'l', 'o']
['a', 'b', 'c']
[1, 2, 3]
[]

Code analysis:

  1. Converting a tuple to a list preserves the element order.
  2. When converting a string, each character becomes an element of the list.
  3. Dictionary conversion only includes the keys.

Example 2: Common Operations on Lists

Examples

# Lists can be modified after creation
lst = list((1, 2, 3))
lst.append(4)    # Add element
lst.insert(0, 0)  # Insert element
print(lst)        # Output: [0, 1, 2, 3, 4]

# List comprehension (more concise way)
lst = [x * 2 for x in range(5)]
print(lst)        # Output: [0, 2, 4, 6, 8]

# Copy list
original = [1, 2, 3]
copy = list(original)
print(copy)       # Output: [1, 2, 3]

Expected output:

[0, 1, 2, 3, 4]
[0, 2, 4, 6, 8]
[1, 2, 3]

Lists are mutable; elements can be added, removed, or modified at any time after creation.


Python3 内置函数Python3 Built-in Functions


Other Extensions