Function to count values of a List

Build the Python len() Function

Python loops and lists practice question

 

Write a Python 3 program that counts the number of elements in a given list. Your program should replicate the functionality of the built-in “len()” function.

To complete this Python practice question, follow these steps:

1. Define a function called “count_elements” that takes a list as input.
2. Inside the function, use a loop to iterate through the elements of the list.
3. Initialize a variable called “count” to keep track of the number of elements.
4. For each iteration, increment the “count” variable by 1.
5. After iterating through all the elements, return the value of “count”.

Your program should not use the built-in “len()” function. Instead, implement your own logic to count the elements. The aim of this type Python practice questions to is to internalize the functions, loops and list concepts.

Source Code

## We define the function to count the values of a given list
def count_elements(input_list):
    count = 0
    for element in input_list:
        count += 1
    return count

## Test
input_list=['45','67','8976','0', '1','2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
count_elements(input_list)
## Output
18

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for Practice
Register New Account
Shopping cart