0

I'm trying to iterate through a list of lists, in order to rearrange it in a new list of lists:

lt = [["a","b","c"],["A","B","C"],["1","2","3"],["4","5","6"]]

lt2 = [[]]*len(lt[0])

for i in range(len(lt[0])):
    for v in range (len(lt)):
        lt2[i].append(lt[v][i])

print(lt2)

I'm expecting the following to happen:
1- i = 0, the nested loop iterates v 4 times, from 0-3
2- i = 1, the nested loop iterates v 4 times again.
3- i = 2, the nested loop iterates v 4 times for the last time.
What I'm planning to achieve is to get the following:

lt2 = [['a','A','1','4'], ['b','B','2','5'],['c','C','3','6']]<br>

So it's a rearranged list of lists
Unexpectedly, I'm getting:

lt2 = [['a', 'A', '1', '4', 'b', 'B', '2', '5', 'c', 'C', '3', '6'], ['a', 'A', '1', '4', 'b', 'B', '2', '5', 'c', 'C', '3', '6'], ['a', 'A', '1', '4', 'b', 'B', '2', '5', 'c', 'C', '3', '6']]<br>
Tom Burrows
  • 2,225
  • 2
  • 29
  • 46
Georges D
  • 351
  • 3
  • 11
  • 1
    try the following: `test_list = [[]] * 3; test_list[0].append(6)` Print out `test_list` and see whats happening. – kmad1729 Jan 16 '17 at 17:34
  • 1
    lt2 = [[x[i] for x in lt] for i in range(3)] – petruz Jan 16 '17 at 17:50
  • Thanks for the comments actually the answer of the question that this question is marked as a duplicate of, gave me the perfect answer, which is that the method I'm using to create an empty list of lists is creating instanced nested lists. After reading and trying that answer, I can imagine the outcome without testing it @kmad1729 :) – Georges D Jan 16 '17 at 17:59

0 Answers0