How to Use the len() Function to Count Elements in a Python List

When working with lists in Python, you often need to know how many data items (elements) are stored in the list. For example, you might need to know how many times to run a for loop, or check if a list is empty (has 0 elements).

Python provides a standard built-in function called len() to get the length of such sequences.


目次

Basic Usage of the len() Function

The len() function returns the “length” or “number of elements” of the object passed as an argument as an integer (int). When you pass a list, it returns the total number of elements in that list.

Syntax:

len(list_object)

Example:

# List of currently active users
active_users = ["guest_01", "member_a", "admin_user", "member_b"]

# Get the number of elements using len()
user_count = len(active_users)

print(f"List content: {active_users}")
print(f"Element count: {user_count}")

Output:

List content: ['guest_01', 'member_a', 'admin_user', 'member_b']
Element count: 4

Since the active_users list contains 4 string elements, len() returns 4.


Empty Lists and len()

The len() function can also be used on an “empty list” that has no elements. In this case, it returns 0.

# List of pending tasks (initially empty)
pending_tasks = []

task_count = len(pending_tasks)

print(f"Task List: {pending_tasks}")
print(f"Task Count: {task_count}")

Output:

Task List: []
Task Count: 0

Using in if Statements

You can check if a list is empty by checking if the number of elements is 0. This is useful when you want to execute code only if data exists.

if len(pending_tasks) == 0:
    print("No tasks to process.")

# (Reference) In Python, you can also use the list itself in the condition
# if not pending_tasks:
#     print("No tasks to process.")

len() Works on Other Objects Too

The len() function is not just for lists. It can be used for other objects that have a concept of length (number of elements or characters).

  • String (str): Returns the total number of characters.
  • Dictionary (dict): Returns the number of key-value pairs.
  • Tuple (tuple): Returns the total number of elements.
message = "Hello"
config = {"host": "localhost", "port": 80}

print(f"Character count of '{message}': {len(message)}")
print(f"Number of keys in config: {len(config)}")

Output:

Character count of 'Hello': 5
Number of keys in config: 2

Summary

  • Use the built-in function len() to get the total number of elements in a list.
  • len(my_list) returns the count as an integer.
  • Running len() on an empty list ([]) returns 0.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次