KnowledgeBoat Logo
|

Computer Science

Predict the output:

fruit = {}
L1 = ['Apple', 'banana', 'apple'] 
for index in L1 :
  if index in fruit: 
    fruit[index] += 1
  else :
    fruit[index] = 1
print(len(fruit))
print(fruit)

Python Dictionaries

26 Likes

Answer

Output
3
{'Apple': 1, 'banana': 1, 'apple': 1} 
Explanation

This python program counts the frequency of each fruit in a list and outputs the number of unique fruits and their frequency. The program does not account for the case sensitivity of the fruit names so "Apple" and "apple" are counted as separate fruits. Here is a step-by-step explanation of the program:

  1. Initialize the variables
    1. The fruit variable is a dictionary that stores the frequency of each fruit.
    2. The L1 variable stores the input list ['Apple', 'banana', 'apple'].
  2. Loop through each fruit index in the list L1
    1. If the fruit already exists as a key in the fruit dictionary, its value is incremented by 1.
    2. If the fruit is not in the fruit dictionary, a new key is added with a value of 1.
  3. The length of the fruit dictionary is printed to the console, indicating the number of unique fruits.
  4. The fruit dictionary is printed to the console, showing the frequency of each fruit.

Answered By

2 Likes


Related Questions