3

The idea is to append values to list element in a list. So there is a list, which consists of lists. For example, there is a list 'a', consisting of two lists "A" and "B". I would like to create a new list, consisting of the first list of 'a' (a[0]) and append a value 1 to it without modifying the original list 'a'.

a=[["A"],["B"]]
b = a[0]
b.append("1")
print a

The result of print a:

[['A', '1'], ['B']]

But I want is that the list 'a' does not change. The list b equals ['A', '1'] is what I need.

student
  • 511
  • 1
  • 5
  • 20

1 Answers1

1

Copy a[0] with a[0][:]:

>>> a = [["A"],["B"]]
>>> b = a[0][:]
>>> b.append("1")
>>> a
[['A'], ['B']]
>>> b
['A', '1']
Mike Müller
  • 82,630
  • 20
  • 166
  • 161