1

Python appends to all lists(like they are different pointer for the same memory address) when decalred with one line syntax(this: a = b = c []) but no such case with non-iterables or seperate declaration.

Same thing was causing a bug in my program when I used append()
and after some(a lot) debugging I found that this was causing the bug.

Example code with output:

a = b = c = []
a.append(1)
b.append(2)

print("1st", a, b, c)
# Output: 1st [1, 2] [1, 2] [1, 2]

# But not with some other types or when reassigned
# Reassigning list
a = b = c = []
a = [1, 2, 3]

print("2nd", a, b, c)
# Output:2nd [1, 2, 3] [] []

# Multi-line for control
a = []
b = []
c = []
a.append(1)
b.apend(2)

print("3rd", a, b, c)
# Output:3rd [1] [2] []

Seperate output of program

Output:
1st [1, 2] [1, 2] [1, 2]
2nd [1, 2, 3] [] []
3rd [1] [2] []

Are the lists something like different references but to the same memory address when assigned with one line syntax.

AVX-42
  • 755
  • 2
  • 13
  • 21

3 Answers3

2
a = b = c = []  # a, b, and c are assigned to the same list

The first is assigning those 3 variable names to the same list. Both appends are appending to the same list.

a = [1, 2, 3]  # a is assigned to a new list

In the second, a is getting assigned to a new list [1,2,3].

a = []  # a gets its own list
b = []  # b gets its own list
c = []  # c gets its own list

In the third, a b c are each assigned to their own lists.

Christopher Nuccio
  • 596
  • 1
  • 9
  • 21
1

like they are different pointer for the same memory address

They are, that is how python works in this instance.

Zac Wimer
  • 89
  • 5
-2

list instances are mutable, so the line

a = b = c = []

creates one list which is accessible through 3 different names.

This is not the case with non-mutable data structures (tuple, int, str).

Ralf
  • 16,086
  • 4
  • 44
  • 68
  • 3
    Mutability is totally irrelevant. All Python objects have exactly the same semantics when it comes to assignment. Immutable types *simply don't expose mutator methods*. – juanpa.arrivillaga May 16 '19 at 19:04