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

Python Copying a List

Python Copying a List

Document Object Reference Manual Python3 Examples

Define a list and copy its elements into another list.

Example 1

def

clone_runoob

(

li1

)

:

    li_copy

=

li1

[

:

]

   

return

li_copy

 

li1

=

[

4

,

8

,

2

,

10

,

15

,

18

]

li2

=

clone_runoob

(

li1

)

print

(

"Original list:"

,

li1

)

print

(

"List after copying:"

,

li2

)

The output of the above example is:


原始列表: [4, 8, 2, 10, 15, 18]
复制后列表: [4, 8, 2, 10, 15, 18]

Example 2: using the extend() method

def

clone_runoob

(

li1

)

:

    li_copy

=

[

]

    li_copy.

extend

(

li1

)

   

return

li_copy

 

li1

=

[

4

,

8

,

2

,

10

,

15

,

18

]

li2

=

clone_runoob

(

li1

)

print

(

"Original list:"

,

li1

)

print

(

"List after copying:"

,

li2

)

The output of the above example is:


原始列表: [4, 8, 2, 10, 15, 18]
复制后列表: [4, 8, 2, 10, 15, 18]

Example 3: using the list() method

def

clone_runoob

(

li1

)

:

    li_copy

=

list

(

li1

)

   

return

li_copy

 

li1

=

[

4

,

8

,

2

,

10

,

15

,

18

]

li2

=

clone_runoob

(

li1

)

print

(

"Original list:"

,

li1

)

print

(

"List after copying:"

,

li2

)

The output of the above example is:


原始列表: [4, 8, 2, 10, 15, 18]
复制后列表: [4, 8, 2, 10, 15, 18]

Document Object Reference Manual Python3 Examples