Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you write <code>[x]*3</code> you get, essentially, the list <code>[x, x, x]</code>. That is, a list with 3 references to the same <code>x</code>. When you then modify this single <code>x</code> it is visible via all three references to it.</p> <p>To fix it, you need to make sure that you create a new list at each position. One way to do it is</p> <pre><code>[[1]*4 for n in range(3)] </code></pre> <p>which will reevaluate <code>[1]*4</code> each time instead of evaluating it once and making 3 references to 1 list.</p> <hr> <p>You might wonder why <code>*</code> can't make independent objects the way the list comprehension does. That's because the multiplication operator <code>*</code> operates on objects, without seeing expressions. When you use <code>*</code> to multiply <code>[[1] * 4]</code> by 3, <code>*</code> only sees the 1-element list <code>[[1] * 4]</code> evaluates to, not the <code>[[1] * 4</code> expression text. <code>*</code> has no idea how to make copies of that element, no idea how to reevaluate <code>[[1] * 4]</code>, and no idea you even want copies, and in general, there might not even be a way to copy the element.</p> <p>The only option <code>*</code> has is to make new references to the existing sublist instead of trying to make new sublists. Anything else would be inconsistent or require major redesigning of fundamental language design decisions.</p> <p>In contrast, a list comprehension reevaluates the element expression on every iteration. <code>[[1] * 4 for n in range(3)]</code> reevaluates <code>[1] * 4</code> every time for the same reason <code>[x**2 for x in range(3)]</code> reevaluates <code>x**2</code> every time. Every evaluation of <code>[1] * 4</code> generates a new list, so the list comprehension does what you wanted.</p> <p>Incidentally, <code>[1] * 4</code> also doesn't copy the elements of <code>[1]</code>, but that doesn't matter, since integers are immutable. You can't do something like <code>1.value = 2</code> and turn a 1 into a 2.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload