Count function for a list with mixed elements -integers and strings

Hi All - I am trying to apply a count function to a list of mixed elements but it seems it does not work? Do you know how to use the count in such cases.

pizzas = [(1, ‘cheese’), (2, ‘mushrooms’), (2, ‘olives’), (2, ‘pepperoni’), (3, ‘sausage’), (6, ‘pineapple’), (7, ‘anchovies’)]

Hi @kitin19 - welcome to the forum.

I think the problem you’re running up against is that the list.count() function won’t examine the contents of the tuples which make up your list.

One way you could work around it would be:

pizzas = [(1, "cheese"),(2, "mushrooms"), (2, "olives"),
          (2, "pepperoni"), (3, "sausage"), (6, "pineapple"), 
          (7, "anchovies")]
num_two_dollar_slices = len([slice for slice in pizzas if slice[0] == 2])
>>> 3

There could be other ways of doing it, but that one works. :slight_smile:


Thanks very much for your reply! Very useful.

1 Like

The technique that @thepitycoder presented works well by getting inside the tuples to perform the count.

Another option is to unpack each tuple by specifying two variables within the for clause of the list comprehension, as follows:

num_two_dollar_slices = len([price for price, topping in pizzas if price == 2])

The following conforms more closely to the instructions by literally counting the number of occurrences of 2 in the list, but that renders it a bit clumsy:

num_two_dollar_slices = [price for price, topping in pizzas if price == 2].count(2)

If you would like to generalize the process as a function, this will perform the task:

def price_count(price_to_count):
  return len([price for price, topping in pizzas if price == price_to_count])

# count $1.00 slices
num_one_dollar_slices = price_count(1)

# count $2.00 slices
num_two_dollar_slices = price_count(2)

This post was edited on July 8, 2019 to refine some of the descriptive text.

1 Like

Hello, I had the same problem.

At the end I created the function below. It was necesary to look at the “for and while” instructios, and the help of the two partners that aswered before. Thanks a lot.

I hope it helps

def count_price (pizzas, price):

# We define variables. count is the variable that we save the number of pizzas with the price chosen
    j = len(pizzas)
    count = 0
    while i < j:
# First gets the i tupple, and we save it in the variable tuplep
        tuplep = pizzas[i]
# Then we get the price catching the first position [0] of the tuple i (tuplep) and we save it in a variable called number
        number = tuplep[0]
# Then if number is equal to price we add one to the variable count
        if number == price:
            count +=1
    return count

num_two_dollar_slices = count_price(pizzas, 2)

print (num_two_dollar_slices)

Hey @angelcorreaesteban04 , I corrected the formatting for your code.

You can check out this post as a reference on how to do this, so that the forum correctly displays what you’ve written. :slight_smile: