2

I'm a beginner in programming and am currently taking a Python class. I'm using PyCharm, and was writing a function to merge dictionaries. I have the number of arguments set to variable, and wanted to store the number of arguments actually being passed through when the function is called as a variable to be used in a while loop. While typing it out, the __len__() method came up, and it seemed to do exactly that. I was wondering if someone can explain how this works? I tried searching for the answer but I'm not completely sure I understand how __len__() works, and how it worked in this case.

Thank you, Melissa

def merge_dicts(*dict):
    num_of_dicts = dict.__len__() 
Melissa
  • 55
  • 5
  • 2
    possible duplicate of [difference between len() and .\_\_len\_\_()?](http://stackoverflow.com/questions/2481421/difference-between-len-and-len) – styvane Sep 30 '15 at 03:58
  • 1
    it works because `*dicts` (please use an S, or some other name, like Eevee said) means make a list of all the arguments. and you can take the length of a list. In python, nothing (well, very little) is special - a list of arguments is just a list like any other. – Corley Brigman Sep 30 '15 at 04:05
  • 1
    Just for your information, most people use the naming convention `(*args, **kwargs)`, when those parameters are used. – mpontillo Sep 30 '15 at 04:13
  • thank you, that was where my lack of understanding came in - that *dicts creates a list, which allows the use of the len() method. will make the edits @Eevee suggested. thanks everyone! – Melissa Sep 30 '15 at 04:14
  • 3
    @CorleyBrigman: `*args` varargs packing actually receives the arguments as a `tuple`, not a `list`. Doesn't much matter if you never try to mutate it, but the distinction is important in many cases. – ShadowRanger Sep 30 '15 at 04:14
  • Related: [What do *args and **kwargs mean?](https://stackoverflow.com/questions/287085/what-do-args-and-kwargs-mean) – smci Aug 25 '18 at 02:19

1 Answers1

4

You just want len(dicts). (And I would strongly recommend calling it dicts, both because it's plural and because it doesn't shadow the built-in dict.)

__len__ is the method that implements len() for various types, but there's very very rarely any good reason to call a __dunder__ method directly.

Eevee
  • 47,412
  • 11
  • 95
  • 127