0

I have a list which contains list of words.

Example:

[['A','B','C'],['D'],['E']]

To implement this i have create an empty list of list of size 4.

list1=[list()] *4

and then tried append element one by one.

list1[0].append('A')
list1[0].append('B')
list1[0].append('C')
list1[1].append('D')
list1[2].append('E')

Output:

[['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'C', 'D', 'E']]

Expected was:

[['A','B','C'],['D'],['E']]
Joby Wilson Mathews
  • 10,528
  • 6
  • 54
  • 53

2 Answers2

2

Your issue is that here :

list1=[list()] *4

you are making copies of the same list object. You are essentially adding the elements to the same list every time.

To fix:

list1=[[] for i in range(3)]


list1[0].append('A')
list1[0].append('B')
list1[0].append('C')
list1[1].append('D')
list1[2].append('E')

Which gives your expected result.

Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
0

The initialization method you used creates a list of four pointers that all point to the same list. You shouldn't use the asterisk operator in this case.

Samuel O.D.
  • 346
  • 2
  • 13