Scrollable Nav Bar

Python Tuples and Sets

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.


1. 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)
Code language: PHP (php)

You can also build a set from any iterable (like a list, tuple, or string):

my_set = set(['a', 'b', 'c'])
print(my_set)

my_set = set(('a', 'b', 'c'))  # from a tuple
print(my_set)
Code language: PHP (php)

Important: {} creates an empty dictionary, not an empty set. Use set() for an empty set:

empty_set = set()
print(type(empty_set))
Code language: JavaScript (javascript)

[Creating sets and printing output]


2. 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.

my_list = ['b', 'c', 'c', 'b', 'a']
unique_values = set(my_list)
print(unique_values)
Code language: JavaScript (javascript)

If you need the result back as a list:

deduped_list = list(set(my_list))
print(deduped_list)
Code language: PHP (php)

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:

my_list = ['b', 'c', 'c', 'b', 'a']
deduped_preserve_order = list(dict.fromkeys(my_list))
print(deduped_preserve_order)
Code language: PHP (php)

[ Deduplication results showing changed order vs preserved order]


3. 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.

my_set = {'a', 'b', 'c'}
# print(my_set[0])  # ❌ TypeError: 'set' object is not subscriptable
Code language: PHP (php)

In 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]


4. 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)
Code language: PHP (php)

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 (very common)

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
Code language: PHP (php)

Getting the size

Use len():

print(len(my_set))
Code language: PHP (php)

[ Using add(), in, and len()]


5. 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)

my_set = {'a', 'b', 'c'}
my_set.discard('a')
my_set.discard('x')  # no error
print(my_set)
Code language: PHP (php)

remove() removes if present (error if missing)

my_set = {'a', 'b', 'c'}
my_set.remove('b')
# my_set.remove('x')  # ❌ KeyError
print(my_set)
Code language: PHP (php)

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)
Code language: PHP (php)

If you want to empty a set, you can repeatedly pop until it’s empty:

my_set = {'a', 'b', 'c', 'd'}
while len(my_set) > 0:
    print('popped:', my_set.pop())

print('now:', my_set)
Code language: PHP (php)

[ pop() behavior and emptying a set]


6. 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)
Code language: PHP (php)

Example: checking overlap between two groups

python_students = {'Asha', 'Ravi', 'Neha'}
ml_students = {'Neha', 'Kiran', 'Ravi'}

common = python_students & ml_students
print(common)
Code language: PHP (php)

2. 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)
Code language: PHP (php)

You can read an element by index:

print(my_tuple[0])  # 'a'
Code language: PHP (php)

[ Creating and indexing a tuple]


7. 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
Code language: PHP (php)

This immutability is not a limitation—it’s a feature. A tuple clearly communicates: “These values belong together and shouldn’t be changed.”


8. 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)
Code language: PHP (php)

Or a simple “row” of data:

employee = ('E102', 'Asha', 'Engineering')
Code language: JavaScript (javascript)

9. 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.

def returns_multiple_values():
    return 1, 2, 3

result = returns_multiple_values()
print(result)
print(type(result))
Code language: PHP (php)

You’ll see that result is a tuple.

Parentheses are optional (but readability matters)

Python doesn’t require parentheses to define a tuple:

my_tuple = 1, 2, 3
print(my_tuple)
print(type(my_tuple))
Code language: PHP (php)

This works, but in real projects many developers still prefer parentheses when declaring a tuple directly, because it looks clearer.


10. 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)
Code language: PHP (php)

This is clean, readable, and extremely common in Python.

[Unpacking multiple return values]


11. 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)

12. Practice:

  1. Create a list with repeated values, convert it to a set, and observe how duplicates are removed.
  2. Build a set of your favorite technologies and check if 'python' is in the set.
  3. Write a function that returns (min_value, max_value) for a list of numbers, then unpack the result into two variables.