-1

I have a list made out of several lists (e.g. lst = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]), and I created this list appending another list to it with a for loop:

for i in range(0, 3):
    lst.append([1, 2, 3])

Then I tried to modify one of those lists (lst[0].remove(1)).

But when I do that, all of the lists get modified, and the list looks like that: [[2, 3], [2, 3], [2, 3]]

Is there any way I can modify the list so it looks like [[2, 3], [1, 2, 3], [1, 2, 3]]?

I also tried to use the del function, but I didn't seem to work.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    @MattPitkin You provided enough info to constitute an answer, so please post it as actual answer and delete the comments - the code will be more readable, at least. – matszwecja Aug 11 '23 at 08:37
  • The code you have shown already does what you want. – mkrieger1 Aug 11 '23 at 08:57

2 Answers2

2

If you are actually creating the list in the way you state, then the removal of an item should work as expected. What I assume you you're actually doing is creating a list by appending the same list to it multiple times, i.e.,

sublist = [1, 2, 3]
mylist = []
for _ in range(3)
    mylist.append(sublist)

In this case the outer mylist just contains pointers/references to the same object, so if you modify one you modify them all.

Instead you need to make sure you append copies of the list, e.g.,

sublist = [1, 2, 3]
mylist = []
for _ in range(3):
    mylist.append(list(sublist))  # using list creates a copy

Then you'll find that:

mylist[0].remove(1)

gives

print(mylist)
[[2, 3], [1, 2, 3], [1, 2, 3]]

Note: calling your list list is not a good idea as is overwrites the built-in Python list.

P.S. - this is a common issue encountered by people starting out in Python, see, e.g., List of lists changes reflected across sublists unexpectedly and many of the linked questions.

Matt Pitkin
  • 3,989
  • 1
  • 18
  • 32
0

this works as expected

li = []

for i in range(0, 3):
  li.append([1, 2, 3])

li[0].remove(1)

print(li)

Output:

[[2, 3], [1, 2, 3], [1, 2, 3]]
yashaswi k
  • 668
  • 7
  • 17
  • 1
    `list([1, 2, 3])` is a bit redundant. the `list` constructor is used in Matts answer because he only uses a reference to a list, so he must copy it. you use the literal syntax, so a new list is created in each loop anyways – Aemyl Aug 11 '23 at 08:45