[Tutor] solution for for loop?

Alan Gauld alan.gauld at btinternet.com
Sat Oct 25 14:17:46 CEST 2014


On 25/10/14 04:17, Clayton Kirkwood wrote:
> description_string=code_string=''
> description = code = ‘a’
>
> for (description_position, code_position) in (description, code):
>      print(description_position,code_position)
>
> I have tried variations on this for statement, and it doesn’t work:<)))

No surprise there, it doesn't make sense.

> Both description and code have the same size array.

There are no arrays in sight. Both names refer to the same
object: the letter 'a'. You then put the names in a tuple
which is what I assume you mean? . But tuples are very
different to arrays.

 > I was hoping that some derivative of this for
> would bring in a new description_position
> value, and code_position value.

 From where? You set them up to point to a fixed string.
Where do you suppose Python would find any other values?

> Amongst various trials I have tried dp in d && cp in c; dp, cp in d,c. etc.
>
> This is the error report:
> Traceback (most recent call last):
>    File "C:/Users/Dad/python/stock tracker/raw yahoo scraper codes.py",
> line 80, in <module>
>      for (description_position, code_position) in (description, code):
> ValueError: too many values to unpack (expected 2)

Read the error description then look at your for line closely.

for (description_position, code_position) in (description, code):

That reads:

for aTupleOfNames in aTupleOfValues:

It's trying to iterate over aTupleofValues and then unpack the first 
value into the the two names.

You need a collection as the for loop target to give the for something 
to iterate over. It only needs to contain your tuple (a single element 
collection) but it needs to have something to iterate over. An
example might help:

Using shorter names and literals for brevity:

This is your code:

 >>> for x,y in (1,2): print('ok')

which gives an error because it picks out the first element
of the (1,2) tuple which is 1, and tries to unpack that into
x,y - which it can't.
That's what is happening in your case too.

Now look at:

 >>> for x,y in [(1,2)]: print('ok')

This time the loop picks out the (1,2) tuple as the first
(and only) element of the target list and unpacks to x and y.
So we get ok printed in this case.

> Is there something like what I want?

I don't know because I don't really know what you were trying
to do.

Your code as it stands could just have been written as

description_position, code_position = description, code

But I don't think that really is what you were tying to do.

HTH,
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list