Python len() - Get Length

Updated on September 27, 2024
len() header image

Introduction

The len() function in Python is a built-in utility that returns the number of items in an object. While commonly used to determine the length of lists, strings, and other collections, its utility spans a variety of data types that makes it indispensable in day-to-day programming. Understanding how to use len() efficiently can simplify many tasks in data manipulation, conditional operations, and more.

In this article, you will learn how to effectively utilize the len() function across various Python data structures. Explore practical applications in strings, lists, dictionaries, and other iterable objects to master this fundamental function.

Using len() with Strings

Measure String Length

  1. Initialize a string variable.

  2. Use the len() function to determine its length.

    python
    sample_string = "Hello, world!"
    length = len(sample_string)
    print(length)
    

    This code calculates the number of characters in sample_string, including punctuation and spaces, outputting 13.

Identifying Empty Strings

  1. Check the length of a string to determine if it is empty.

  2. Use the length to control flow or logic within the program.

    python
    empty_string = ""
    if len(empty_string) == 0:
        print("String is empty")
    else:
        print("String is not empty")
    

    By evaluating the length of empty_string, the script decides which print statement to execute. It outputs "String is empty" since the length is 0.

Using len() with Lists

Count Elements in a List

  1. Create a list.

  2. Use len() to find out how many items it contains.

    python
    fruits = ['apple', 'banana', 'cherry']
    print("Number of fruits:", len(fruits))
    

    Here, len(fruits) returns 3, the number of items in the list fruits.

Loop Through a List Using Its Length

  1. Use the length of a list to iterate over its elements with a for loop.

  2. Print each item by accessing it through its index.

    python
    for i in range(len(fruits)):
        print(fruits[i])
    

    The loop runs from 0 to the length of fruits minus one, printing each fruit sequentially.

Using len() with Dictionaries

Determine Dictionary Size

  1. Define a dictionary.

  2. Apply len() to find the number of key-value pairs.

    python
    person = {'name': 'John', 'age': 30, 'city': 'New York'}
    print("Number of entries:", len(person))
    

    The function len(person) accurately counts the dictionary entries, which are three in this example.

Usage with Conditional Statements

  1. Check the size of the dictionary to perform different actions.

  2. The size determination can guide the flow of operations.

    python
    if len(person) > 2:
        print("The dictionary contains more than two entries.")
    else:
        print("The dictionary has two or fewer entries.")
    

    This code uses len(person) to decide between two print statements based on the size of the dictionary.

Conclusion

The len() function in Python is a simple yet powerful tool that helps in determining the size of various data structures. Whether you're checking the length of strings, lists, or dictionaries, len() performs consistently and effectively, providing essential information that drives logic and flow in your programs. As explored, leveraging the len() function can streamline code, especially in loops and conditionals, ensuring your solutions are efficient and clear. Use these techniques to enrich your Python programming skills and handle different data structures with ease.