0

I have a list X = ['xyz']

I use the below commands for appending to another variable.

L = X

L.append(X)

L

Out[109]: ['xyz', [...]]

I am unable to understand why the second element in the new L list is not having the value as 'xyz'

My question is not how to append or extend a list, but in fact about the functionality of Append function, which has been correctly explained by @sinsuren below.

Sarang Manjrekar
  • 1,839
  • 5
  • 31
  • 61

2 Answers2

2

append add X as an element to L. If you want the element inside X to be inserted to L, use extend instead:

>>> X = ['xyz']
>>> L = X
>>> L.extend(X)
>>> L
['xyz', 'xyz']
Uriel
  • 15,579
  • 6
  • 25
  • 46
1

Try this, it will extend the list.

L.extend(X)

But if you want to use append. Use a element like this L.append('abc'). It will give same result or L.append(X[0])

Edit:
You have Appended list to itself. It will recursively append to itself and due to which even L[1] will give you same response. Like L[1] = ['xyz', [...]] . and for more understanding Please refer What's exactly happening in infinite nested lists?

Community
  • 1
  • 1
sinsuren
  • 1,745
  • 2
  • 23
  • 26