Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python 3 print(list, list.pop())? [duplicate]

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?

like image 552
Vibius Avatar asked Jul 18 '17 15:07

Vibius


People also ask

Does list Take duplicates in Python?

Python list can contain duplicate elements.

How do I stop a list duplication in Python?

If the order of the elements is not critical, we can remove duplicates using the Set method and the Numpy unique() function. We can use Pandas functions, OrderedDict, reduce() function, Set + sort() method, and iterative approaches to keep the order of elements.

Does list take duplicate values?

What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.


1 Answers

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.

like image 60
Willem Van Onsem Avatar answered Sep 18 '22 21:09

Willem Van Onsem