How to Count the Number of Strings in a List in Python?

Estimated read time 2 min read

To count the number of strings in a list in Python, you can use a loop or a list comprehension along with the isinstance() function. Here’s an example using a loop:

# Define the list
my_list = [1, "apple", "orange", 3.14, "banana", "grape", "cherry"]

# Initialize a counter
count = 0

# Loop through each element in the list
for item in my_list:
    # Check if the element is a string using isinstance()
    if isinstance(item, str):
        # If it's a string, increment the counter
        count += 1

# Print the count
print("The number of strings in the list is:", count)

In this example, my_list is the list in which you want to count the number of strings. The isinstance() function is used to check if an element in the list is a string or not. If an element is a string, the counter count is incremented. Finally, the count of strings in the list is printed.

Alternatively, you can use a list comprehension along with isinstance() to achieve the same result in a more concise way:

# Define the list
my_list = [1, "apple", "orange", 3.14, "banana", "grape", "cherry"]

# Use a list comprehension to count the number of strings
count = sum(isinstance(item, str) for item in my_list)

# Print the count
print("The number of strings in the list is:", count)

In this example, the isinstance() function is used inside a list comprehension to create a list of boolean values where each value is True if the corresponding element in my_list is a string, and False otherwise. The sum() function is then used to count the number of True values, which represents the count of strings in the list. Finally, the count is printed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply