Updated June 15, 2023
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 Python’s most common built-in functionalities to fetch the properties associated with the dataset we are working on, Specifically length. In this article, we will walk you through how to use the len() function to fetch the length of an array, tuple, dictionary, 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 the 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 want to apply the len() function to a specific column per the requirements? Can this apply to a data frame as well? Let’s take a real-life example 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:
We’ll review the functionality of this program to understand how the len() function works when we pass an integer 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)
You can pass this column to the len() function to calculate the magnitude of the salary drawn with the following statement.
DF["Salary Length"]= DF["Salary"].str.len()
Each row returns a value that the program stores in the “Salary Length” column of the DF data frame. 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. You can handle this with the following statement.
DF["Salary"]= DF["Salary"].astype(float)
Finally, we see the expected results when we print the data frame at the end.
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 of 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 –