Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 List list() Method

The Python list() function

Python3 Built-in Functions Python3 built-in 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

- Type: iterable (tuple, string, dictionary, set, etc.) - Description: the iterable to convert into a list.

Function description


Example

Example 1: converting from other sequences

Example

Convert from a tuple to a list

t

=

(

1

,

2

,

3

,

4

,

5

)

lst

=

list

(

t

)

print

(

lst

)

       

Output: [1, 2, 3, 4, 5]

Convert from a string

s

=

"hello"

lst

=

list

(

s

)

print

(

lst

)

       

Output: ['h', 'e', 'l', 'l', 'o']

Convert from a dictionary (keys only)

d

=

{

"a"

:

1

,

"b"

:

2

,

"c"

:

3

}

lst

=

list

(

d

)

print

(

lst

)

       

Output: ['a', 'b', 'c']

Convert from a set

s

=

{

3

,

1

,

2

}

lst

=

list

(

s

)

print

(

lst

)

       

Output: [1, 2, 3] (automatically 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. 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

print

(

lst

)

       

Output: [0, 1, 2, 3, 4]

List comprehension (a more concise approach)

lst

=

[

x *

2

for

x

in

range

(

5

)

]

print

(

lst

)

       

Output: [0, 2, 4, 6, 8]

Copy a 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, so elements can be added, removed, or modified at any time after creation.


Python3 Built-in Functions Python3 built-in function