Last modified: Sep 20, 2023 By Alexander Williams

Python List Size Examples

Example 1: Using the `len()` Function


# Initialize a list
my_list = [1, 2, 3, 4, 5]

# Get the size of the list using the `len()` function
list_size = len(my_list)

# Print the size of the list
print("List Size:", list_size)
    

Output:


List Size: 5
    

Example 2: Using a Loop


# Initialize a list
my_list = [10, 20, 30, 40, 50]

# Initialize a counter
list_size = 0

# Loop through the list to count elements
for _ in my_list:
    list_size += 1

# Print the size of the list
print("List Size:", list_size)
    

Output:


List Size: 5
    

Example 3: Using List Comprehension


# Initialize a list
my_list = ["apple", "banana", "cherry", "date"]

# Get the size of the list using list comprehension
list_size = sum(1 for _ in my_list)

# Print the size of the list
print("List Size:", list_size)
    

Output:


List Size: 4
    

Example 4: Using a While Loop


# Initialize a list
my_list = [True, False, True, False]

# Initialize a counter and index
list_size = 0
index = 0

# Use a while loop to count elements
while index < len(my_list):
    list_size += 1
    index += 1

# Print the size of the list
print("List Size:", list_size)
    

Output:


List Size: 4
    

Example 5: Using the `pandas` Library (for DataFrames)


# Import the pandas library
import pandas as pd

# Initialize a DataFrame (equivalent to a list)
my_list = [1, 2, 3, 4, 5]

# Create a DataFrame
df = pd.DataFrame(my_list)

# Get the size of the DataFrame using the `shape` attribute
list_size = df.shape[0]

# Print the size of the list (DataFrame)
print("List Size:", list_size)
    

Output:


List Size: 5