5

For print() with multiple arguments, I thought it evaluates them one by one. However, the following code

a = [1, 2, 3, 4]
print(a, a[:], a.pop(), a, a[:])

prints

[1, 2, 3] [1, 2, 3, 4] 4 [1, 2, 3] [1, 2, 3]

I thought python would evaluate a first, then a[:], then a.pop(), then a and a[:] again, which would print

[1, 2, 3, 4] [1, 2, 3, 4] 4 [1, 2, 3] [1, 2, 3]

So how exactly does this work?

Vibius
  • 171
  • 1
  • 7
  • Relevant: https://stackoverflow.com/questions/42761707/what-is-the-order-of-evaluation-in-python-when-using-pop-list-1-and – Chris_Rands Jul 18 '17 at 15:35

1 Answers1

6

In case you call a function (any function). The arguments are first evaluated left-to-right. So your code is equivalent to:

arg1 = a
arg2 = a[:]
arg3 = a.pop()
arg4 = a[:]
print(arg1,arg2,arg3,arg4)

(of course the variables arg1, arg2, etc. do not exist at the Python level)

arg1 will thus refer to the same list as a, next we make a shallow copy of a and store it in arg2, then we pop from a and the last item is stored in arg3 and finally we make another shallow copy (of a at that point) and store it in arg4.

So that means that:

arg1 = a         # arg1 = a = [1,2,3,4]
arg2 = a[:]      # arg2 = [1,2,3,4]
arg3 = a.pop()   # arg1 = a = [1,2,3], arg3 = 4
arg4 = a[:]      # arg4 = [1,2,3]
print(arg1,arg2,arg3,arg4)

Next the print(..) statement is called with these argument and thus printed like we see in the comments. So it will print:

[1, 2, 3] [1, 2, 3, 4] 4 [1, 2, 3]

The important part is thus that a.pop() will not only return the last element of the list referenced by both a and arg1, but also modify that list (remove the last element). So as a result arg1 and a still refer to the same list, but it is modified.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555