Python Forum
How can I print the number of unique elements in a list?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I print the number of unique elements in a list?
#1
Using the dictionary below, I'm supposed to create a function that returns the number of unique items in the "items" list.

shopping_cart = {
    "tax": .08,
    "items": [
        {
            "title": "orange juice",
            "price": 3.99,
            "quantity": 1
        },
        {
            "title": "rice",
            "price": 1.99,
            "quantity": 3
        },
        {
            "title": "beans",
            "price": 0.99,
            "quantity": 3
        },
        {
            "title": "chili sauce",
            "price": 2.99,
            "quantity": 1
        },
        {
            "title": "chocolate",
            "price": 0.75,
            "quantity": 9
        }
    ]
}
I've created the code below which outputs the number of items (5), but I need the code to only count unique items. For example, if two items in this list were identical, it should return 4 (since only 4 items would be unique in that case). How can I accomplish this?

def get_tax_rate(d):
    print (d['tax'])
Output:
5
Reply


Messages In This Thread
How can I print the number of unique elements in a list? - by AnOddGirl - Mar-19-2020, 10:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to sort a list with duplicates and return their unique indices. Echoroom 3 3,505 Sep-23-2022, 07:53 AM
Last Post: deanhystad
  help with adding duplicates elements together in a list 2ECC3O 5 2,041 Sep-10-2022, 07:11 AM
Last Post: 2ECC3O
  list digit into number Voldyy 2 1,542 Jul-10-2022, 06:13 PM
Last Post: deanhystad
  Displaying list correspond to the column number danlopek14q 9 3,973 Aug-27-2021, 04:32 AM
Last Post: naughtyCat
  How to convert every even number in a list to odd? Bruizeh 4 3,761 Aug-27-2021, 03:04 AM
Last Post: naughtyCat
  Unexpected behavior accessing list elements. tonyflute 2 2,269 Apr-09-2021, 02:36 PM
Last Post: tonyflute
  How to find difference between elements in a list? Using beginner Basics only. Anklebiter 8 4,360 Nov-19-2020, 07:43 PM
Last Post: Anklebiter
  How to print all iterations of min and max for a 2D list alaina 4 2,915 Nov-11-2020, 05:53 AM
Last Post: alaina
  Why does this function print empty list? hhydration 1 1,540 Oct-28-2020, 02:03 AM
Last Post: deanhystad
  Get 5 most unique combinations of elements in a 2D list wanttolearn 1 2,316 Sep-24-2020, 02:26 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020