Q.Consider a list:
list1 = [6,7,8,9]
What is the difference between the following operations on list1:
a. list1 * 2
b. list1 *= 2
c. list1 = list1 * 2
list1 = [6,7,8,9]
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Same resulting value, three different fates for list1: list1 * 2 is a discarded expression (list1 unchanged), list1 *= 2 mutates the existing list object in place, and list1 = list1 * 2 creates a new object and re-points the name at it.
The idea. The * operator on a list means repetition. The question is really about the difference between an expression, an in-place (augmented) assignment, and a rebinding assignment — i.e. about object identity and mutation, which matter as soon as two names refer to the same list.
a. list1 * 2 — a bare expression.
list1 = [6,7,8,9]
print(list1 * 2)
print(list1)
[6, 7, 8, 9, 6, 7, 8, 9]
[6, 7, 8, 9]
The repeated list is created, (here) printed, and thrown away. list1 itself is never modified — unless you assign the result somewhere.
b. list1 *= 2 — in-place repetition. For mutable types, the augmented assignment extends the same list object:
list1 = [6,7,8,9]
alias = list1 # second name for the SAME object
list1 *= 2
print(list1)
print(alias) # alias sees the change
print(list1 is alias)
[6, 7, 8, 9, 6, 7, 8, 9]
[6, 7, 8, 9, 6, 7, 8, 9]
True
c. list1 = list1 * 2 — new object, rebound name.
list1 = [6,7,8,9]
alias = list1
list1 = list1 * 2 # builds a NEW list, name re-points to it
print(list1)
print(alias) # alias still refers to the OLD object
print(list1 is alias)
[6, 7, 8, 9, 6, 7, 8, 9]
[6, 7, 8, 9]
False
Summary table:
| Operation | Value of list1 afterwards | Same object as before? | Aliases affected? |
|---|---|---|---| …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.