List of elements with their frequency in a list


This Python code calculates the frequency of each element in a list and stores the results in a dictionary called element_frequencies. Here's how the code works:

  • numbers = [1, 2, 2, 3, 4, 4, 4, 5]: This line initializes a variable named numbers and assigns it a list containing several numbers, including some duplicates.
  • element_frequencies = {num: numbers.count(num) for num in set(numbers)}: This line of code initializes a variable named element_frequencies and assigns it the result of a dictionary comprehension.
    • set(numbers): This part converts the list numbers into a set, which removes duplicate elements and retains only the unique elements. This step ensures that each unique element is counted only once.
    • {num: numbers.count(num) for num in set(numbers)} : This is the dictionary comprehension itself. It iterates through the unique elements in the set and, for each element (num), counts how many times it appears in the original list numbers using the numbers.count(num) method. The result is a key-value pair in the dictionary, where the key is the element, and the value is its frequency.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(element_frequencies): This line of code prints the element_frequencies dictionary (which contains the frequencies of elements) to the console.

Source Code

numbers = [1, 2, 2, 3, 4, 4, 4, 5]
element_frequencies = {num: numbers.count(num) for num in set(numbers)}
print(numbers)
print(element_frequencies)

Output

[1, 2, 2, 3, 4, 4, 4, 5]
{1: 1, 2: 2, 3: 1, 4: 3, 5: 1}

Example Programs