w3resource

Python: Count the number of elements in a list within a specified range

Python List: Exercise - 31 with Solution

Count Elements in List Within Range

Write a Python program to count the number of elements in a list within a specified range.

Python: Count the number of elements in a list within a specified range

Sample Solution:

Python Code:

# Define a function named 'count_range_in_list' that counts the number of elements within a specified range
def count_range_in_list(li, min, max):
    # Initialize a counter 'ctr' to keep track of the count
    ctr = 0

    # Iterate through the elements 'x' in the input list 'li'
    for x in li:
        # Check if 'x' falls within the specified range [min, max]
        if min <= x <= max:
            # If 'x' is within the range, increment the counter 'ctr'
            ctr += 1

    # Return the final count of elements that fall within the range
    return ctr

# Define a list 'list1' containing numeric elements
list1 = [10, 20, 30, 40, 40, 40, 70, 80, 99]

# Call the 'count_range_in_list' function with 'list1' and the range [40, 100], and print the result
print(count_range_in_list(list1, 40, 100))

# Define another list 'list2' containing character elements
list2 = ['a', 'b', 'c', 'd', 'e', 'f']

# Call the 'count_range_in_list' function with 'list2' and the range ['a', 'e'], and print the result
print(count_range_in_list(list2, 'a', 'e')) 

Sample Output:

6                                                                                                             
5

Flowchart:

Flowchart: Count the number of elements in a list within a specified range

Python Code Editor:

Previous: Write a Python program to get the frequency of the elements in a list.
Next: Write a Python program to check whether a list contains a sublist.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-31.php