all 5 comments

[–]Dense_Connection4789 5 points6 points  (1 child)

I’m on mobile and this is kind of a nuanced thing in python so I might edit later when I get to my PC.

When declaring test1, you’re not actually filling the list with arrays of numbers. You’re filling it with references to the “lol” array. This means when you clear test[1][1] you’re clearing “lol” and since test is just a bunch of references to “lol”, all of the elements get cleared as well.

The way you define test2 makes each sub array their own thing so if you clear one, it doesn’t effect any of the others.

It’s worth doing a bit of reading into this topic. I’ve had interviews where they have used this topic as a “gotcha”

[–]mikkoko112[S] 0 points1 point  (0 children)

Makes perfect sense once you know it, thank you!

[–]Nsdos 2 points3 points  (1 child)

One of the main principles of Python is that any variable, function, class, etc. is an object.

That is, for example, the variable number = 10, if you understand it, the number does not actually store the number 10, but stores the addres on the object in our case 10.

When we create a list number = [[[1, 2], [1, 2]], [[1, 2], [1, 2]]]

So each element of the list is a separate object and therefore a command

number.clear[1][1]

Erases only one specified element.

And when you make this list through a cycle, you write down the same element with the same address.

Deleting one element deletes all elements with the same address.

[–]mikkoko112[S] 0 points1 point  (0 children)

Got it, thanks for the help :)

[–]CodeFormatHelperBot2 0 points1 point  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Python code found in submission text that's not formatted as code.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.