Introduction to Python len Function
Python len() function is a pre-defined or inbuilt function that returns the length of the string passed as an argument to it. Python len() function is one of the most common built-in functionalities within python to fetch the properties associated with the dataset that we are working upon, Specifically length. In this article, we will walk you through on how to use the len() function to fetch the length of an array, tuple, dictionary, a column in a dataset & a sample string.
Syntax:
len(str)
Here, a string is passed as an argument & the len() function returns that string’s length.
Examples of Python len Function
Following are the different examples of Python len Function.
Example #1
Code:
# Python program to demonstrate the usage of len() functon in python
# Length of below string is 3
str = "EDU"
print("Length of str1 is:")
print(len(str))
# Length of below string is ?
str2 = "EDU CBA"
print("Length of str2 is:")
print(len(str2))
Output:
What if we have a huge dataset and we want to apply the len() function to a specific column as per the requirements. Can this apply to a data frame as well? Let’s take a real-life example in order to understand the same.
Example #2
Code:
# importing pandas module
import pandas as pd
# reading csv file from url
DF = pd.read_csv("C:/Users/name/Desktop/Projects/abc.csv")
## dropping null value columns to avoid errors as nulls can not be passed on to len() function
DF = DF.dropna()
# converting to string dtype
DF["Salary"]= DF["Salary"].astype(str)
# passing values
DF["Salary Length"]= DF["Salary"].str.len()
# converting back to float dtype
DF["Salary"]= DF["Salary"].astype(float)
# display
DF
Output:
Let’s go through this program’s functionality to understand the usage of the len() function when an integer is passed as an argument.
len(5555)
If an integer is passed as an argument to the len() function as in the case of the above statement as well, then the python client throws the below error:
That’s why we have converted the column salary of the type int into a string using type conversion using the below statement.
DF["Salary"]= DF["Salary"].astype(str)
This column can be passed on to the len() function to calculate the magnitude of the salary drawn using the below statement.
DF["Salary Length"]= DF["Salary"].str.len()
The value returned for each row is returned and stored in the column “Salary Length” of the data frame DF. To revert the data type to the original one for the column named “Salary”, We can use the astype function passing the required data type. Let’s convert it into a floating value. The same can be taken care of using the below statement.
DF["Salary"]= DF["Salary"].astype(float)
Finally, when we print the data frame at the end, we see the expected results.
Example #3
Is len() function also applicable to a tuple? Let’s check that out by taking up another example:
Code:
## Python Program to find the length of a tuple
Tupl = ('Jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
print("The value returned by len() function for this tuple is \n", len(Tupl))
Output:
Example #4
Let’s take another example, wherein we will get the number of elements present in the python dictionary:
Code:
## Python Program to find the length of a dictionary
Dic = {'EDU': 18,'CBA':12,'EDU CBA':22,'EDU EDU':25}
print("The value returned by len() function for this dictionary is \n", len(Dic))
What do you expect from the output of this program?
- Case 1: Length of each element within the dictionary?
- Case 2: Length of the dictionary that is the count of the number of elements present within the dictionary?
Yes, You are right. Case 2 is.
Output:
As we have four elements within in python dictionary. so the len() function will return a value 4.
Example #5
Let’s take another quick example to understand how the len() function deals with the arrays in python.
Code:
## Python Program to find the length of an array
arr = ['EDU','CBA']
print("The value returned by len() function for this array is ", len(arr))
Output:
Recommended Articles
This is a guide to Python len Function. Here we discuss the Introduction to Python len Function along with different examples and code implementation. You may also look at the following articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses