3

I'm not sure how to ask this question properly cause I'm trying to understand something I don't understand yet and therefore I don't know the right terminology to use, but I came across this code snippet in a YouTube tutorial regarding PIL here.

Question

Could somebody please explain what the last line means? I'm guessing it is a Python style of declaring variables I am not familiar with yet and I dont know what it is called so I can't look it up.

import Image

filename = "py.png"
image = Image.open(filename)
size = width, height = image.size

What I've Tried

I've tried to break down the logic of the last line but it doesn't make sense to me:

# assign value of width to size variable?     
size = width 
# assign value of image.size to height variable?
height = image.size 

The problems I see with this are:

  • width is not defined.

  • image.size represents the images dimensions ie (512,512) so that doesn't seem like it would be an appropriate value for height.

I'm sure this is very simple, I just don't get it yet.

1 Answer 1

3

Solution

I think I figured it out by running the following:

>>> size = width, height = 320, 240;
>>> size
(320, 240)
>>> width
320
>>> height
240

So essentially what the code in the original post is saying is:

>>> size = width, height = 512, 512;
>>> size
(512, 512)
>>> width
512
>>> height
512

Which means:

"The variable size is a tuple made of two values (width and height) and their values are 512 and 512 resp".

The mechanics of it haven't really sunk in yet, but good enough for now.

Sign up to request clarification or add additional context in comments.

1 Comment

You need to read it backwards... the , is used to create tuples... - so 512, 512 creates a two element tuple which are unpacked in width, height, then size is assigned to the tuple width, height... In short, width and height contain the individual values, but by use of unpacking, they're also viewed as a tuple for the assignment on the left...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.