w3resource

Python: Count the number of occurrences in a list

Python Basic: Exercise-22 with Solution

Write a Python program to count the number 4 in a given list.

Pictorial Presentation:

Count the number 4 in a given list

Sample Solution:

Python Code:

# Define a function called list_count_4 that takes a list of numbers (nums) as a parameter.
def list_count_4(nums):
  # Initialize a variable count to keep track of the count of occurrences of the number 4.
  count = 0

  # Iterate through each element (num) in the input list (nums).
  for num in nums:
    # Check if the current element (num) is equal to 4.
    if num == 4:
      # If the element is 4, increment the count by 1.
      count = count + 1

  # Return the final count after iterating through the list.
  return count

# Call the list_count_4 function with two different input lists and print the results.
print(list_count_4([1, 4, 6, 7, 4]))  # Output: 2 (There are two occurrences of 4 in the list.)
print(list_count_4([1, 4, 6, 4, 7, 4]))  # Output: 3 (There are three occurrences of 4 in the list.)

Sample Output:

2                                                                                                             
3 

Explanation:

The said code defines a function called "list_count_4" that takes a list of numbers as its argument, "nums". Inside the function, it initializes a variable "count" to zero. Next, it uses a for loop to iterate through each element in the "nums" list. For each iteration, it checks if the current element i.e. num is equal to 4, if true it increments the "count" by 1. After the for loop completes, the function returns the final "count" of how many times the number 4 appears in the list.

The last two lines of code call the function, with the input values ([1, 4, 6, 7, 4]) and ([1, 4, 6, 4, 7, 4]) and print the results.

The first call will return 2, and the second call will return 3.

Flowchart:

Flowchart: Count the number 4 in a given list.

Python Code Editor:

 

Previous: Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
Next: Write a Python program to get the n (non-negative integer) copies of the first 2 characters of a given string. Return the n copies of the whole string if the length is less than 2.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.