0

example code:

my_list = [[]] * 4
my_list[2].append(3)
print my_list

expected: [[], [], [3], []]

actual: [[3], [3], [3], [3]]

My inference is that the nested lists are copies of one another. Is there a way to achieve the expected?

cbalawat
  • 1,133
  • 1
  • 9
  • 14

1 Answers1

0

Assign 3 a different way

l = [[]] * 4
l[2] = [3]
print(l)
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 rows.py
[[], [], [3], []]
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
  • I don't think that's answering the question. How would you use append specifically? Sometimes the lists are of unknown length. – sirj Dec 28 '21 at 10:32
  • His goal was to append 3 to the the l[2] , he was specific. And he defined his list as 4. Even if the list was an unknown length l[2] is still in it unless it’s a smaller nested list. – vash_the_stampede Dec 29 '21 at 23:28