Python check length and size of string.

In this python article, We are going to learn python built-in functions
len() and getsizeof().

  • len(): Using len() function we can check the length of an object(count number of items). In short len() function returns us the number of elements present in the sequence (List, Tuple, String, range) or in a mapping (Dictionary or set).
  • getsizeof(): Using getsizeof() function we can check how much memory in bytes is allocated to store a complete object.

Introduction to len() function:

Basically len() function queries the container and returns the number of items present in that container. So we have to pass the object whose length we want to calculate as an argument to the len function.

Arguments to a len() function can be of following data types such as sequence (string, list, tuple) or a mapping (Dictionary or a set).

Python len and getsizeof function

Syntax of len() function:


Lets see how python len() function works with sample object of each data type.

Example 1: Use of len() function with string, tuple, list and range objects.

Sample_string = "Best Python blog."

# Output:

# List of mixed data:
mixed_data_list = [1, 2.5, "Paul", 0.5]

# Output:

# Tuple of mixed data:
mixed_data_tuple = (8, 'John', 2.8, 65)

# Output:

Sample_range = range(1, 15)

# Output:

If you want to get information about python data types then please go through the articles below:

Example 2: Use of len() function with Dictionary and Set objects.

# Create an object of dictionary data type.
school_dictionary = {'john':10, 'Ben':15, 'Alex':18, 'smith':25, 'Harry':32}

# Output:

# Create an object of Set data type.
Sample_Set = {2.5, 'tuple_var', 22, 'Happy', 'John', 'smith', 90}

# Output:

If you want to get information about python data types then please go through the articles below:

Use of getsizeof() function:

Python getsizeof() function is used to get the memory in bytes allocated to store a specific object. getsizeof() function is present in sys module. So to use getsizeof() function we first have to import it in our program.

Suppose you have created a string and now you want to know how much memory is consumed by that string.

from sys import getsizeof
Sample_string = "Best Python blog."
print("Total characters in sample string are:",len(Sample_string))
print("Memory consumed by sample string is:",getsizeof(Sample_string))

# Output:
Total characters in sample string are: 17
Memory consumed by sample string is: 66

In above example, we can see the difference between python len() and python getsizeof() function. len() function returns us the number of elements present is string whereas getsizeof() function returns us the memory consumed by that object.

Continue reading:

  1. Python Built in method – String count.
  2. List comprehension in python.

Leave a Comment