2

Sorry to ask a dumb question, but could somebody tell me what the following means

for ctype, (codename, name) in searched_perms:

I don't understand what's going on the parenthesis. for ctype in serached_perms: would make sense.

I realise that the answer is in the python docs somewhere but since I don't know what I'm looking for, it's difficult to find the explaination.

1

4 Answers 4

6

This is practically equivalent to

for x in search_perms:
     ctype, y = x
     codename, name = y

or

for x in search_perms:
    ctype = x[0]
    codename = x[1][0]
    name = x[1][1]

i.e., it unpacks the items from search_perms as pairs, then unpacks the second item of each pair as a pair as well.

Example:

>>> d = {"ham": "yes", "spam": "no", "eggs": "please"}
>>> for k, v in d.iteritems():
...     print("%s? %s" % (k, v))
...     
eggs? please
ham? yes
spam? no
>>> for i, (k, v) in enumerate(d.iteritems()):
...     print("question %d: %s? %s" % (i, k, v))
...     
question 0: eggs? please
question 1: ham? yes
question 2: spam? no

This works because enumerate(d.iteritems()) generates pairs where each second element is again a pair:

>>> list(enumerate(d.iteritems()))
[(0, ('eggs', 'please')), (1, ('ham', 'yes')), (2, ('spam', 'no'))]
Sign up to request clarification or add additional context in comments.

Comments

1

ctype, (codename, name) is the same thing as (ctype, (codename, name)). Therefore, searched_perms needs to be a sequence of things of the form (a,(b,c)), and on each loop iteration the variables ctype, codename, name will be set to a,b,c.

Comments

1

Your list searchedparams should looks something like this:

In [1]: L = []

In [2]: L.append(('a', ('b', 'c')))

In [3]: L.append(('d', ('e', 'f')))

In [4]: L
Out[4]: [('a', ('b', 'c')), ('d', ('e', 'f'))]

In [6]: for ctype, (codename, name) in L:
    print ctype, codename, name
   ...: 
a b c
d e f

('a', ('b', 'c')) is a tuple of 2 values, where the right value is also a tuple of two values.

Comments

0

It means that searched_perms is an iterable that returns two elements during iteration: the first one is ctype and the second is a tuple, composed of another two elements: (codename, name). So searched_perms looks something like this:

[[ctype1, (code1, name1)], [ctype2, (code2, name2)], ...]

The syntax for ctype, (codename, name) in searched_perms allows the extraction of all the contents in searched_perms, element by element.

Comments

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.