'How to not add duplicate list values but instead add a counter to count each item

elif int(groceriesInput) in range(len(groceries)+1):
    optionSelect = input("\nAdd " + (groceries[int(groceriesInput)- 1][0]) + " to the cart? (y or n): ")
    if optionSelect == "y" or optionSelect == "Y":
        if groceries[int(groceriesInput)-1] in cart:
            os.system('cls')
        else:
            os.system('cls')
            cart.append(groceries[int(groceriesInput)- 1])

How would I add a counter before each item without adding a duplicate item to the list?

My function builds the list from reading a file.

For example this is the output I want:

2 milk

instead of:

milk
milk


Solution 1:[1]

In order for the print to be the number of times a product appears, we can use List Comprehensions and then len to calculate this amount and generate a print as desired by you.

Create the entire list, then do the following:

a = [['eggs', 1.99], ['milk', 3.59], ['salmon', 9.99], ['milk', 3.25], ['bean dip', 2.99], ['milk', 8.99], ['Greek yogurt', 4.99], ['brocoli', 2.29], ['tomatos', 3.19], ['apples', 5.99], ['parmesan cheese', 10.99], ['chips', 3.69], ['muesli', 4.99], ['parmesan cheese', 6.39], ['goat cheese', 5.19], ['parmesan cheese', 5.99], ['Pinot Noir', 18.5]]


d = list(set([b[0] for b in a]))
for unique in d:
    total_match = [b for b in a if b[0] == unique]
    print(f'{len(total_match)} {unique}')

Print:

1 Pinot Noir
1 tomatos
1 muesli
1 eggs
1 brocoli
1 Greek yogurt
1 bean dip
1 apples
1 goat cheese
3 parmesan cheese
1 chips
3 milk
1 salmon

If you want to keep the sequence of products intact, use it this way:

a = [['eggs', 1.99], ['milk', 3.59], ['salmon', 9.99], ['milk', 3.25], ['bean dip', 2.99], ['milk', 8.99], ['Greek yogurt', 4.99], ['brocoli', 2.29], ['tomatos', 3.19], ['apples', 5.99], ['parmesan cheese', 10.99], ['chips', 3.69], ['muesli', 4.99], ['parmesan cheese', 6.39], ['goat cheese', 5.19], ['parmesan cheese', 5.99], ['Pinot Noir', 18.5]]

d = list(dict.fromkeys([b[0] for b in a]))
for unique in d:
    total_match = [b for b in a if b[0] == unique]
    print(f'{len(total_match)} {unique}')

Print:

1 eggs
3 milk
1 salmon
1 bean dip
1 Greek yogurt
1 brocoli
1 tomatos
1 apples
3 parmesan cheese
1 chips
1 muesli
1 goat cheese
1 Pinot Noir

Note: I modified some values in the list so that milk and parmesan cheese not have a total of 1, but 3 so you can see that each item is being sum.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1