Python Sets
Curly braces keep each value once. drinks is written as tea, then water, then tea again. The second tea is not stored. What remains is tea and water, so the length is 2.
A tuple could keep the order you wrote, and the same value could sit twice. This group does neither. The second tea has nowhere to sit.
There is no place number. drinks[0] stops the program. If you printed the group, water might show before tea. That order is not a promise, and this program does not print the group.
"tea" in drinks asks whether tea is there. The answer is True. "soup" in drinks asks the same about soup. Soup was never written, so the answer is False. This is not a place. It is only yes or no.
drinks = {"tea", "water", "tea"}
print(len(drinks))
print("tea" in drinks)
print("soup" in drinks)
The screen shows 2, then True, then False. The 2 is the length after the second tea was dropped. True means tea is in the group. False means soup is not.
drinks.add("soup") would put soup in, and the length would become 3. drinks.add("tea") would leave the length at 2, because tea is already there. Neither line is in the program above.
An empty group of this kind is written set(). The braces with nothing inside, {}, are not that empty group. They belong to the next page.
The next page pairs a name with a value. This page only stores values, and it stores each of them once. It does not pair anything.
One tea, not two
- What length does the program write?
- Is tea in the group?
- Is soup in the group?
- What happens if you write drinks[0]?
soup was never stored
The screen is 2, then True, then False. tea is in the group, and the second tea did not raise the length. soup is not in the group. drinks[0] stops. drinks.add("tea") would leave the length at 2. The next page pairs a name with a value.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top