Home › Python with Chai › Lesson 17
Sets: how many customers?
Python with Chai, lesson 17 of 20. A short Hinglish video, simple English notes and code you can run, free.
Open the interactive lesson with Run button
The idea
A list keeps duplicates: Ravi came twice, so len(log) says 4 when only 3 people came.
A set keeps each value only once: set(log) drops the double, and len() gives the real count.
add() puts in a new value (an existing one changes nothing), and in answers True or False. A set has no fixed order.
The code
log = ["Ravi", "Neha", "Ravi", "Amit"]
unique = set(log)
print(len(log), len(unique))
unique.add("Sita")
print("Ravi" in unique, "Zoya" in unique)
print(len(unique))
Output:
4 3 True False 4
Try it yourself
- Add "Ravi" again with add(). Did len(unique) change?
- Turn the set back into a list with list(unique) and print it.
Remember
Set = a guest list with no doubles.
← Default values: less sugar · datetime: shop timing →
All lessons: Python with Chai