Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does extra parameter mean in this for-loop in Python?

I have come across a for-loop that is unusual to me. What does method mean in this for-loop?

for method, config in self.myList.items():

like image 378
TruMan1 Avatar asked Apr 15 '15 16:04

TruMan1


People also ask

What are the 3 parameters used in a for loop in Python?

Range with three parameters: start, end, step.

How many parameters does a for loop have?

Contrary to other languages, in Smalltalk a for-loop is not a language construct but defined in the class Number as a method with two parameters, the end value and a closure, using self as start value.

Can we use 2 variables in for loop Python?

No. Using enumerate() we'll get an enumerate object. Save this answer.


2 Answers

items() is a method used on python dictionaries to return an iterable holding tuples for each of the dictionary's keys and their corresponding value.

In Python you can unpack lists and tuples into variables using the method you've shown.

e.g.:

item1, item2 = [1,2]
# now we have item1 = 1, item2 = 2

Therefore, assuming self.myList is a dict, method and config would relate to the key and value in each tuple for that iteration respectively.

If self.myList is not a dict, I would assume it either inherits from dict or it's items() method is similar (you would know better).

like image 146
NDevox Avatar answered Sep 21 '22 22:09

NDevox


It's unpacking a tuple returned from the items() call into the method and config variables.

like image 44
AlG Avatar answered Sep 19 '22 22:09

AlG