0

I am trying to make a row into a column. That is, I have row = [2, 4, 8], and I need [[2], [4], [8]]. So I made this code:

row = [2, 4, 8]
column = [[]] * 3
for y in range(3):
    column[y].append(row[y])

column has to be [[2], [], []] after the first loop. But it was [[2], [2], [2]]. Does anyone know what's the matter?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Comet
  • 63
  • 2
  • 8
  • See [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – khelwood Sep 21 '19 at 05:55
  • @khelwood Oh, that solved! Thank you! – Comet Sep 21 '19 at 06:02

3 Answers3

0

Try this out:

raw = [2, 4, 8]
column =[]

for case in raw:
    column.append([case])

Concerning your question it should be because a list containing a value and the memory of the next iteration.

a = [1]
b = a
b[0] = 2
print(a)  # return [2]
Vincent Bénet
  • 1,212
  • 6
  • 20
  • Actually, in my real code, the for-loop is inside another loop, and the column is defined outside the loop. I need ````board = [[2, a1, b1], [4, a2, b2], [8, a3, b3]]````. – Comet Sep 21 '19 at 05:56
0

You can just use:

column = [[i] for i in row]

as per the following transcript:

Python 3.6.5 (default, Apr  1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> row = [2, 4, 8]
>>> column = [[i] for i in row]
>>> print(column)
[[2], [4], [8]]
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0
#see if this soves your issue
row = [2, 4, 8]
col=[]
for i in row:
    col.append([i])
TBhavnani
  • 721
  • 7
  • 12