0

I wanted to know how I can print the quantity of the items in a list in Python. For example:

list1 = ["hello", "goodbye", "hello"]
message = ", ".join(list1)
print(message)

I would like my output to be "2x hello, 1x goodbye". I have not found any library that does something like that, but I just started coding so I might be missing something. If you know any library that does this or if you have any clue on how I could do it, I am open to any advice.

Thank you in advance!

Edit: thank you all for the big help. All the answers were useful and solved the problem.

6 Answers6

2

You can use Counter to do this:

from collections import Counter

list1 = ["hello", "goodbye", "hello"]
counts = Counter(list1)
message = ", ".join(f"{counts[key]}x {key}" for key in counts)
print(message)

This code uses f-strings and list comphrensions.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • Just to nitpick, there's no list comprehension here, it's a generator expression. If you make it a list comprehension, it [should run faster](https://stackoverflow.com/a/62865237/6243352). – ggorlen Nov 14 '20 at 14:59
0

You can use a Counter collection for that matter: https://docs.python.org/3/library/collections.html#collections.Counter

JPery
  • 69
  • 6
0
list1 = ["hello", "goodbye", "hello"]
unique_values = set(list1)
result = []
for value in unique_values:
    result.append("{}x {}".format(list1.count(value), value))

message = ", ".join(result)
print(message)
0

you can create dictionary with each element in your list as key to the dictionary. and then print or use the dict for counting the occurance.

# temp_dict will have the count for each element.
temp_dict={}
for item in list1:
    if item in temp_dict.keys():
        temp_dict[item]+=1
    else:
        temp_dict[item]=1
#temp_dict will contain the count of each element in your list1.
print(temp_dict)
for key,value in temp_dict.items():
    print(str(value)+'x'+key)
Amit Kumar
  • 613
  • 3
  • 15
0

@Aplet123 already gave an answer but if you don't want to import Counter, you can use the below code.

list1 = ["hello", "goodbye", "hello"]
x= [str(list1.count(i))+'x'+i for i in set(list1)]
message = ", ".join(x)
print(message)

A DUBEY
  • 806
  • 6
  • 20
  • While this is nice as (effectively) a one-liner, time complexity here is quadratic. Additionally, if OP wants the result string sorted by count descending or by occurrence location (specification is unclear), this won't do it--the ordering of the `set` is arbitrary. – ggorlen Nov 14 '20 at 15:05
0

you can use pandas in this example:

import pandas as pd
list1 = ["hello", "goodbye", "hello"]
counts = Counter(list1)
a = pd.Series(counts)
for i in range(2):
    print(a[i] , "x" , a.index[i])

output:

2 x  hello
1 x  goodbye