Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

difference between "function()" and "function"

I see

  1. df["col2"] = df["col1"].apply(len)
  2. len(df["col1"])

My question is,
why use "len" function without parenthesis in 1, but use it with parenthesis in 2?

what is the difference between the two?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I see this kind of occasion a lot, where using a function with and without parenthesis.
Can someone explain me what exactly is going on?

Thanks.

>Solution :

The first example that you mentioned(the above code) maps the function len to the target variable df["col1"]

df["col2"] = df["col1"].apply(len)

Whenever we have to map a function to any iterable object, the syntax needs the function to be without parenthesis.
In your case, df["col1"] must be having elements whose length can be calculated. And it will return a Pandas Series will lengths of all the elements.
Take the following example.

a = ["1", "2","3","4"]
z = list( map( int, a ) )  >> [1, 2, 3, 4]

Here, we mapped the builtin int function(which does typecasting), to the entire list.

The second example that you mentioned would give out the length of the df["col1"] series.

len(df["col1"])

It won’t do any operations on the elements within that Series.
Take the following example.

a = ["1", "2","3","4"]
z = len(a)  >> 4

Since, on both the occasions, the function len was fed an iterable object, it didn’t give any error. But, the outputs are completely different as I explained!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading