Start learning free

LESSON 99 OF 410 · LISTS I

List Length in Python

Lesson Read the full explanation

We can get the length of a list using the len() function like this:

ourList = [50, 40, 30]

# Printing the length:
print(len(ourList)) # Output: 3

# Changing the list:
ourList.pop()

# Printing the new length:
print(len(ourList)) # Output: 2

Using len()

We can use the len() function to access items from the end of a list.

Because lists are 0-indexed, the index of the last item is length - 1:

ourList = [50, 40, 30]

# Printing the last item:
print(ourList[len(ourList) - 1]) # Output: 30

# Printing the second to last item:
print(ourList[len(ourList) - 2]) # Output: 40

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    PYTHON · LISTS I

    Array Length in Python, explained

    Python len(): How to Get the Length of a List

    len() is one of Python's most-used built-in functions. It tells you how many items are in a list — and that number unlocks a surprising amount of power: safe indexing, loop control, size validation, progress tracking, and more. Virtually every non-trivial program that works with lists calls len() at some point.

    Basic Usage

    scores = [95, 82, 74, 88, 91]
    
    print(len(scores))   # 5
    
    # After removing an item, the length updates:
    scores.pop()
    print(len(scores))   # 4
    
    # Empty list:
    empty = []
    print(len(empty))    # 0
    

    Using len() to Access the Last Element

    Because lists are zero-indexed, the last item is always at index len(list) - 1. (Though in modern Python, list[-1] is the simpler way to do this.)

    items = ["alpha", "beta", "gamma", "delta"]
    
    # Both of these access the last element:
    print(items[len(items) - 1])   # delta
    print(items[-1])               # delta  (cleaner)
    
    # Second to last:
    print(items[len(items) - 2])   # gamma
    print(items[-2])               # gamma  (cleaner)
    

    len() Enables Safe Indexing

    Before accessing an index, check that it actually exists — len() makes this easy:

    data = [10, 20, 30]
    
    # Guard against IndexError:
    index = 5
    if index < len(data):
        print(data[index])
    else:
        print(f"Index {index} is out of range (list has {len(data)} items)")
    # Index 5 is out of range (list has 3 items)
    

    Real-World Example: Progress Tracking

    tasks = ["Design", "Build", "Test", "Deploy", "Launch"]
    completed = ["Design", "Build"]
    
    total = len(tasks)
    done  = len(completed)
    remaining = total - done
    
    print(f"Progress: {done}/{total} tasks complete")   # Progress: 2/5 tasks complete
    print(f"Remaining: {remaining} tasks")              # Remaining: 3 tasks
    percent = (done / total) * 100
    print(f"{percent:.0f}% done")                       # 40% done
    

    len() Works on Strings Too

    The same function works on strings, tuples, and dictionaries — not just lists:

    word = "algorithm"
    print(len(word))   # 9
    
    coords = (10, 20, 30)
    print(len(coords))  # 3
    
    info = {"name": "Alex", "age": 28}
    print(len(info))    # 2  (number of key-value pairs)
    

    Common Mistakes to Avoid

    • Off-by-one errors: The last valid index is len(list) - 1, not len(list). Using list[len(list)] always raises IndexError.
    • Comparing to length when you should check membership: To check if an item exists, use if x in my_list, not if len(my_list) > 0.
    • Calling len() on a non-sequence: len(42) raises a TypeError. It only works on collections.
    nums = [1, 2, 3]
    
    # Common mistake — accessing len() as the last index:
    # print(nums[len(nums)])   # IndexError!
    
    # Correct:
    print(nums[len(nums) - 1])   # 3
    print(nums[-1])               # 3  (simpler)
    

    Key Takeaways

    • len(my_list) returns the number of elements — an integer you can use like any other number.
    • Valid indices range from 0 to len(list) - 1; going outside this range crashes with IndexError.
    • Use len() to guard against index errors, control loops, and track progress.
    • len() also works on strings, tuples, and dictionaries.

    What to Learn Next

    Now that you can measure a list, the natural next step is iterating over it. Learn for loops to process every element automatically, and range(len(list)) for index-based iteration. You'll use these patterns constantly in real Python programs.

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free