In Python, you can use slicing to create a copy of a list. The b = a[:]
statement creates a new list b
that contains all the elements of list a
but is a separate object, meaning that if you modify b
, a
won't change, and vice versa.
Here is an example:
main.py136 chars6 lines
In this example, we assign a
a list of four integers. Then, we create a copy of a
and assign it to b
using the slice notation. We modify the first element of b
, and then print out both a
and b
. Note that a
is unchanged, while b
has been modified.
Using slicing to create a copy of a list is a very common idiomatic Python technique.
gistlibby LogSnag