Home > OS >  How to copy list elements in python
How to copy list elements in python

Time:12-11

regarding the code below:

A = [[1, 2], [3, 4]]
A[0] = A[1]
B = A[:][0]
B[0] = 5
print(A)
print(B)

I'm wondering why printing B gives [5, 4].

I thought that B = A[:][0] is the same as A[0][0], A[1][0], which would then be [3, 3]. Then, B[0] = 5, so it would print [5, 3].

Could someone kindly clear up my confusion, thanks.

CodePudding user response:

after this line:

A[0] = A[1]

A = [[3,4],[3,4]]

A[:] will return A itself, so when you access 0, you will get [3,4]

B = A[:][0]

and after putting 5, B = [5,4]

CodePudding user response:

Here is your confusion:

I thought that B = A[:][0] is the same as A[0][0], A[1][0]

It's not. The : symbol in Python isn't used for that sort of shorthand like in some other languages. A[:] simply returns a copy of A, so A[:][0] is equivalent to A[0], which in this context is [3, 4].

(The more general use of the : is for an operation called slicing, which is when you copy only part of a list, from a given starting index to a given end index. If we omit the indices, they default to the start and end of the entire list, so we copy the whole thing.)

CodePudding user response:

Using the copy() method is relatively straightforward.

a = [[1, 2], [3, 4]]
b = a.copy()

print(a)
print(b)

result

[[1, 2], [3, 4]]
[[1, 2], [3, 4]]

If you want to make copies of the nested lists, then you would extend to this:

a = [[1, 2], [3, 4]]
b = [a[0].copy(), a[1].copy()]
  • Related