Rascalpi
Posts: 13
Joined: Sun May 13, 2018 3:55 pm

what does this code do...?

Thu Jun 14, 2018 1:15 pm

Hi
From the URL:

http://www.cl.cam.ac.uk/~db434/raspi/blob_detection/

there is the following line of code:

Code: Select all

red, green, blue = image[x, y]
also further down:

Code: Select all

image[x, y] = 0, 0, 0
I'm new to Python (used to C) so the simultaneous assignment concept is new.
I presume the individual RGB values are being passed to/from the array - but how exactly?

regards
Russell

scotty101
Posts: 2987
Joined: Fri Jun 08, 2012 6:03 pm

Re: what does this code do...?

Thu Jun 14, 2018 1:27 pm

Python can return complex types, in this case it returns a tuple.

Code: Select all

this_is_a_tuple = (1, 2, 3, 4)
You can get the different parts to this in two different ways, long handed way

Code: Select all

part1 = this_is_a_tuple[0]
part2 = this_is_a_tuple[1]
part3 = this_is_a_tuple[2]
part4 = this_is_a_tuple[3]
or unpack them all at once

Code: Select all

part1, part2, part3, part4 = this_is_a_tuple
You can even decide that you don't want all of them and use the underscore symbol to ignore 1 or many parts. This will get parts1, 2 and 4 but ignore part 3.

Code: Select all

part1, part2, _, part4 = this_is_a_tuple
When a function returns as a tuple you can grab the entire structure

Code: Select all

RGB = getColor(x,y)
or you can get the different parts

Code: Select all

R, G, B = getColor(x,y)
The same in reverse works with assignments to a variable.

Does that help in explaining it?
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Rascalpi
Posts: 13
Joined: Sun May 13, 2018 3:55 pm

Re: what does this code do...?

Thu Jun 14, 2018 1:52 pm

Many thanks for the reply - most helpful
Russell

User avatar
Paeryn
Posts: 2055
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: what does this code do...?

Thu Jun 14, 2018 7:44 pm

scotty101 wrote:
Thu Jun 14, 2018 1:27 pm
You can even decide that you don't want all of them and use the underscore symbol to ignore 1 or many parts. This will get parts1, 2 and 4 but ignore part 3.

Code: Select all

part1, part2, _, part4 = this_is_a_tuple
Technically the underscore doesn't ignore a value, an underscore is a variable name just like part1 so it gets assigned to like all the others.
She who travels light — forgot something.

Return to “Python”

Who is online

Users browsing this forum: No registered users and 9 guests