Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Can some explain how this expression is evaluated in python?

Can someone explain what's going on "behind the scenes" in the below expression?

arr[i], mx = mx, max(arr[i], mx)

Take for example :

arr[i] = 5
mx = -1

So in the "first" part of the expression arr[i] gets set to -1, but what I'm having trouble grasping is why arr[i] remains 5 when evaluating the second part of the expression.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,989 Points
# Given
arr[i] = 5
mx = -1
arr[i], mx = mx, max(arr[i], mx)
# becomes
arr[i], mx = -1, max(5, -1)
# becomes
arr[i], mx = -1, 5
# tuple on right is assigned to tuple on left
# arr[i] becomes -1
# mx becomes 5
>>> arr = [0, 5, 10, 15]
>>> i = 1
>>> arr[i]
5
>>> mx = -1
>>> arr[i], mx = mx, max(arr[i], mx)
>>> arr
[0, -1, 10, 15]
>>> mx
5

Post back if you need more help. Good luck!!

That explains everything. Thank you so much!!