0

If I have code to append 1 list into another:

nlis = [2, 4, 6, 8]
k = []
k.append(nlis)
print(k)
for i in range(4):
    nlis[i] += 1
k.append(nlis)
print(k)

For some reason this outputs:

[[2, 4, 6, 8]]
[[3, 5, 7, 9], [3, 5, 7, 9]]

The [2, 4, 6, 8] becomes [3, 5, 7, 8].

How can I make it so that this outputs:

[2, 4, 6, 8]
[[2, 4, 6, 8], [3, 5, 7, 9]]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 2
    You need to append a copy of the list, not the list itself: `k.append(nlis[:])`. – zondo Jul 18 '18 at 02:08
  • I edited my answer – U13-Forward Jul 18 '18 at 02:14
  • It's working properly. You append the same list to another list twice, and you increment every value in that same list – juanpa.arrivillaga Jul 18 '18 at 02:17
  • I don't want to copy my list because in my real program that will make this take 100 of lists. –  Jul 18 '18 at 02:17
  • When you assign to `nlis` (its elements, specifically) you're reusing its memory. You either avoid this, or copy from there. – YiFei Jul 18 '18 at 02:20
  • @Nexus you can either copy your list or not copy the list and use the same list over and over again, sharing the elements. On a modern machine, you can copy 100's of lists in fractions of a second. Why do you care? – juanpa.arrivillaga Jul 18 '18 at 06:54

2 Answers2

1

Try this:

nlis = [2, 4, 6, 8]
nlis2=[]
nlis2.extend(nlis)
k = []
k.append(nlis2)
k.append(nlis)
print(k[0])
for i in range(4):
    nlis[i] += 1
print(k)

Output:

[2, 4, 6, 8]

[[2, 4, 6, 8], [3, 5, 7, 9]]

Or:

nlis = [2, 4, 6, 8]
k = []
k.append(nlis)
print(k[0])
nlis2=nlis[:]
for i in range(4):
    nlis2[i] += 1
k.append(nlis2)
print(k)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

.append() will add whatever you put in it as a single value in your list. Instead, use .extend(). As in k.append(nlis).

Paulo Costa
  • 965
  • 2
  • 10
  • 15