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?
Python list can contain duplicate elements.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With