Python gives you multiple ways to store collections of values. Two of the most useful (and often confused) are sets and tuples.
- Use a set when you care about uniqueness and fast membership checks.
- Use a tuple when you care about fixed structure and you want a sequence that should not change.
This tutorial walks through both, step by step, with examples you can run immediately.
Sets: A Collection of Unique Values
A set is a collection where duplicate values are automatically removed, and the order is not guaranteed. Think of it like a bag of items—values can be present or not present, but there is no “first” or “last” element you can reliably refer to.
Creating a set
You can create a set using curly braces or with the set() constructor.
my_set = {'a', 'b', 'c'}
print(my_set)You can also build a set from any iterable (like a list, tuple, or string):
Example:
my_set = set(['a', 'b', 'c'])
print(my_set)
my_set = set(('a', 'b', 'c')) # from a tuple
print(my_set)
Important: {} creates an empty dictionary, not an empty set. Use set() for an empty set:
Example :
empty_set = set()
print(type(empty_set))
[ Creating sets and printing output]
Removing Duplicates Using a Set
Because sets only keep unique values, a common pattern is to deduplicate a list by converting it to a set.
Example :
my_list = ['b', 'c', 'c', 'b', 'a']
unique_values = set(my_list)
print(unique_values)
If you need the result back as a list:
deduped_list = list(set(my_list))<br>print(deduped_list)A critical detail: sets are unordered
When you convert a list to a set (and back), the order may change. If you must preserve order while removing duplicates, you can do:
Example:
my_list = ['b', 'c', 'c', 'b', 'a']
deduped_preserve_order = list(dict.fromkeys(my_list))
print(deduped_preserve_order)
[Deduplication results showing \ed order]
Why Sets Are Not “Subscriptable”
A list is ordered, so you can do my_list[0] to get the first element. But a set does not have a stable order, so indexing doesn’t make sense.
Example:
my_set = {'a', 'b', 'c'}
# print(my_set[0]) # ❌ TypeError: 'set' object is not subscriptableIn Python, an object is called subscriptable if you can access its elements with bracket syntax (like obj[index]). Sets don’t support that because there is no guaranteed ordering.
TypeError when indexing a set]
Adding and Checking Elements in a Set
Adding items
Use add() to put a new element into a set:
my_set = {'a', 'b', 'c'}
my_set.add('d')
print(my_set)
This is different from lists, where append() adds an element to the end. With sets, it’s more like “tossing it into the bag.”
Checking membership
Membership checks in sets are fast and clean:
my_set = {'a', 'b', 'c', 'd'}
print('a' in my_set) # True
print('z' in my_set) # False
Getting the size
Use len():
print(len(my_set))
[Using add(), in, and len()]
Removing Elements From a Set
Sets give you a few ways to remove items. The two most useful are discard() and remove().
discard() removes if present (no error if missing)
Example:
my_set = {'a', 'b', 'c'}
my_set.discard('a')
my_set.discard('x') # no error
print(my_set)remove() removes if present (error if missing)
Example:
my_set = {'a', 'b', 'c'}
my_set.remove('b')
# my_set.remove('x') # ❌ KeyError
print(my_set)
pop() removes and returns an arbitrary element
pop() pulls out and returns some element from the set and removes it. It is not the “last” item like a list.
my_set = {'a', 'b', 'c', 'd'}
item = my_set.pop()
print(item)
print(my_set)
If you want to empty a set, you can repeatedly pop until it’s empty:
Example:
my_set = {'a', 'b', 'c', 'd'}
while len(my_set) > 0:
print('popped:', my_set.pop())
print('now:', my_set)
pop() behavior and emptying a set]
Common Set Use Cases
Sets shine when your problem is about uniqueness or fast membership checks.
Example: tracking unique visitors
visited_users = set()
visited_users.add('u101')
visited_users.add('u205')
visited_users.add('u101') # duplicate ignored
print(visited_users)
print('u205' in visited_users)
Example: checking overlap between two groups
python_students = {'Asha', 'Ravi', 'Neha'}
ml_students = {'Neha', 'Kiran', 'Ravi'}
common = python_students & ml_students
print(common)
Tuples: An Ordered, Immutable Sequence
A tuple is like a list in that it is ordered and subscriptable (you can index it). The key difference is that a tuple is immutable—once created, you cannot change its contents.
Creating a tuple
Tuples are usually written using parentheses:
my_tuple = ('a', 'b', 'c')
print(my_tuple)You can read an element by index:
print(my_tuple[0]) # 'a'[Creating and indexing a tuple]
Immutability: Why You Can’t Modify a Tuple
Trying to assign a new value to an existing position will raise an error:
my_tuple = ('a', 'b', 'c')
# my_tuple[0] = 'd' # ❌ TypeError: 'tuple' object does not support item assignment
This immutability is not a limitation—it’s a feature. A tuple clearly communicates: “These values belong together and shouldn’t be changed.”
Why Use Tuples?
Tuples are efficient
Because tuples can’t grow or shrink, Python can store them more compactly than lists in many cases. For everyday programming, you don’t always need to think about performance, but it’s a nice bonus.
Tuples represent fixed “records”
Tuples work well when you’re grouping a small number of values that form one unit, like coordinates:
point = (10, 25) # (x, y)Or a simple “row” of data:
employee = ('E102', 'Asha', 'Engineering')
Returning Multiple Values: Tuple Packing
A very Pythonic pattern is returning multiple values from a function. When you separate values with commas, Python returns them as a tuple.
Example:
def returns_multiple_values():
return 1, 2, 3
result = returns_multiple_values()
print(result)
print(type(result))
You’ll see that result is a tuple.
Parentheses are optional
Python doesn’t require parentheses to define a tuple:
my_tuple = 1, 2, 3
print(my_tuple)
print(type(my_tuple))
This works, but in real projects many developers still prefer parentheses when declaring a tuple directly, because it looks clearer.
Unpacking Tuples Into Multiple Variables
The most elegant part of tuple usage is unpacking: assigning multiple variables at once.
def returns_multiple_values():
return 1, 2, 3
a, b, c = returns_multiple_values()
print(a)
print(b)
print(c)
This is clean, readable, and extremely common in Python.
[Unpacking multiple return values]
Sets vs Tuples: Choosing the Right One
If you remember only one thing, remember this:
- Choose a set when you need unique values and you don’t care about order.
- Choose a tuple when you need a fixed, ordered group of values that should not change.
Quick comparison with simple examples
# Set: uniqueness, order not guaranteed
colors = {'red', 'blue', 'blue'}
print(colors)
# Tuple: fixed, ordered
rgb = (255, 0, 0)
print(rgb[0])
Code language: PHP (php)Practice
- Create a list with repeated values, convert it to a set, and observe how duplicates are removed.
- Build a set of your favorite technologies and check if
'python'is in the set. - Write a function that returns
(min_value, max_value)for a list of numbers, then unpack the result into two variables.
