0

I have two lists, similar to these

listA = ['apples','apples','oranges','pears','pears','watermelons','..']
listB = ['apples','oranges','pears','watermenols','...']

So the listA has just a list of fruits, where potential duplicates are in a row. The listB has each fruit, but only once and in the same order as listA.

Is it possible to count (and print) the number of each fruit, for example like this apples 2 orange 1 pears 1 etc

I think you could do it with two loops, but I'm not quite sure how the loops should be...

edit: This should be done WITHOUT any fancy imports and stuff, so just the basics like loops and lists

thanks! :)

PythoNoob
  • 5
  • 3

1 Answers1

0

The Pythonic Way to Count Objects is to use Python’s Counter from collections

from collections import Counter

listA = ['apples','apples','oranges','pears','pears','watermelons',]
res = dict(Counter(listA))
print (res)

# {'apples': 2, 'oranges': 1, 'pears': 2, 'watermelons': 1}

basic way:

listA = ['apples','apples','oranges','pears','pears','watermelons',]
result = {}

for fruit in listA:
   if fruit in result:
       result[fruit] += 1
   else:
       result[fruit] = 1

print(result)
# {'apples': 2, 'oranges': 1, 'pears': 2, 'watermelons': 1}
ncica
  • 7,015
  • 1
  • 15
  • 37
  • Is it possible to do this without a counter? I have read around and many people have told that counter is one way, but we are not supposed to use it yet (This problem is part of a course i am taking in high school and we have not been taught the usage of counter yet) – PythoNoob Nov 11 '21 at 15:55
  • @PythoNoob I edit my post – ncica Nov 11 '21 at 16:03
  • Thank you! This worked for me perfectly! :) – PythoNoob Nov 11 '21 at 16:19
  • @PythoNoob Youre welcome, I am glad that I helped – ncica Nov 11 '21 at 18:15