0

i was working with arrays in python and i wanted to insert one array as column in 2d array and i see that for some reason my column is filled with only last element of words[]

words = ['first','second','third','fourth','fifth']
tab = [[None]*5]*len(words)
for i in range(len(words)):
    tab[i][0] = words[i]
for i in range(len(words)):
    print(tab[i])


#output
['fifth', None, None, None, None]
['fifth', None, None, None, None]
['fifth', None, None, None, None]
['fifth', None, None, None, None]
['fifth', None, None, None, None]
Secane
  • 41
  • 2

1 Answers1

1

youre copying values using

[None]*5

and

*len(words)

your need:

words = ['first','second','third','fourth','fifth']
tab = [[[None] for i in range(5)] for i in range(len(words))]
for i in range(len(words)):
    tab[i][0] = words[i]
for i in range(len(words)):
    print(tab[I])

outs

['first', [None], [None], [None], [None]]
['second', [None], [None], [None], [None]]
['third', [None], [None], [None], [None]]
['fourth', [None], [None], [None], [None]]
['fifth', [None], [None], [None], [None]]
>>> 
Timur U
  • 415
  • 2
  • 14