python list tuples dictionaries and set a bit more details
Python Collections Master Guide
Lists, Tuples, Dictionaries, and Sets
This guide covers:
- Concepts
- Syntax
- Real-world examples
- Important methods
- Common mistakes
- Common errors
- Comparisons
- Time complexity basics
- Interview questions
- Practice exercises
- Homework
Table of Contents
- Introduction
- List
- Tuple
- Dictionary
- Set
- Collection Methods Cheat Sheet
- Comparison Table
- Common Beginner Mistakes
- Real-World Combined Example
- Time Complexity Basics
- Interview Questions
- Homework
1. Introduction
Python provides four major collection types:
| Collection | Ordered | Mutable | Duplicates | Access |
|---|---|---|---|---|
| List | ✅ | ✅ | ✅ | Index |
| Tuple | ✅ | ❌ | ✅ | Index |
| Dictionary | ✅ (3.7+) | ✅ | Keys ❌ Values ✅ | Key |
| Set | ❌ | ✅ | ❌ | Membership |
Quick Memory Trick
LIST -> Changeable Collection
TUPLE -> Fixed Collection
DICT -> Key-Value Collection
SET -> Unique Collection
2. LIST
What is a List?
A List is an ordered collection that can be modified after creation.
Syntax
fruits = ["Apple", "Banana", "Orange"]
Real-World Example
shopping = ["Milk", "Bread", "Eggs"]
print(shopping)
Output:
['Milk', 'Bread', 'Eggs']
Accessing Elements
shopping = ["Milk", "Bread", "Eggs"]
print(shopping[0])
print(shopping[-1])
Output:
Milk
Eggs
Updating Elements
shopping[1] = "Brown Bread"
Most Important List Methods
append()
Adds item at end.
numbers = [1, 2, 3]
numbers.append(4)
print(numbers)
Output:
[1, 2, 3, 4]
extend()
Adds multiple elements.
numbers = [1, 2]
numbers.extend([3, 4, 5])
print(numbers)
Output:
[1, 2, 3, 4, 5]
insert()
numbers = [1, 2, 3]
numbers.insert(1, 100)
print(numbers)
Output:
[1, 100, 2, 3]
remove()
Removes first occurrence.
numbers = [1, 2, 3]
numbers.remove(2)
print(numbers)
Output:
[1, 3]
pop()
Removes and returns element.
numbers = [1, 2, 3]
x = numbers.pop()
print(x)
print(numbers)
Output:
3
[1, 2]
clear()
numbers = [1, 2, 3]
numbers.clear()
print(numbers)
Output:
[]
index()
fruits = ["Apple", "Banana", "Orange"]
print(fruits.index("Banana"))
Output:
1
count()
numbers = [1, 2, 2, 2, 3]
print(numbers.count(2))
Output:
3
sort()
numbers = [5, 1, 4, 2]
numbers.sort()
print(numbers)
Output:
[1, 2, 4, 5]
reverse()
numbers.reverse()
copy()
a = [1, 2, 3]
b = a.copy()
print(b)
Useful Built-in Functions
numbers = [10, 20, 30]
print(len(numbers))
print(max(numbers))
print(min(numbers))
print(sum(numbers))
Common Errors
IndexError
data = [1, 2]
print(data[10])
Output:
IndexError: list index out of range
ValueError
data = [1, 2]
data.remove(5)
Output:
ValueError
3. TUPLE
What is a Tuple?
A Tuple is an ordered but immutable collection.
Syntax
data = (1, 2, 3)
Real-World Example
coordinate = (20.2961, 85.8245)
print(coordinate)
Tuple Methods
Tuple has very few methods because it cannot be modified.
count()
numbers = (1, 2, 2, 3)
print(numbers.count(2))
Output:
2
index()
numbers = (10, 20, 30)
print(numbers.index(20))
Output:
1
Tuple Unpacking
name, age = ("Rahul", 20)
print(name)
print(age)
Returning Multiple Values
def get_user():
return ("Rahul", 20)
name, age = get_user()
Common Errors
TypeError
data = (1, 2, 3)
data[0] = 100
Output:
TypeError
ValueError
name, age, city = ("Rahul", 20)
Output:
ValueError
Beginner Mistake
x = (5)
Output:
<class 'int'>
Correct:
x = (5,)
4. DICTIONARY
What is a Dictionary?
Stores data using key-value pairs.
Syntax
student = {
"name": "Rahul",
"age": 20
}
Real-World Example
employee = {
"id": 101,
"name": "John",
"salary": 50000
}
Accessing Values
print(employee["name"])
Most Important Dictionary Methods
get()
Safe access.
print(employee.get("salary"))
keys()
print(employee.keys())
values()
print(employee.values())
items()
print(employee.items())
update()
employee.update({"city": "Bhubaneswar"})
pop()
employee.pop("salary")
popitem()
Removes last item.
employee.popitem()
clear()
employee.clear()
copy()
new_employee = employee.copy()
setdefault()
employee.setdefault("country", "India")
Adds key only if absent.
Nested Dictionary
employee = {
"name": "John",
"address": {
"city": "Bhubaneswar",
"state": "Odisha"
}
}
print(employee["address"]["city"])
Iterating
for key, value in employee.items():
print(key, value)
Common Errors
KeyError
student = {"name": "Rahul"}
print(student["age"])
Output:
KeyError
Safe:
student.get("age")
Unhashable Type
data = {
[1, 2]: "test"
}
Output:
TypeError: unhashable type: 'list'
5. SET
What is a Set?
A Set stores unique values only.
Syntax
skills = {"Python", "SQL"}
Removing Duplicates
numbers = [1,1,2,2,3,3]
unique = set(numbers)
print(unique)
Output:
{1,2,3}
Most Important Set Methods
add()
skills.add("Java")
Example
skills = set()
# print(type(skills))
print(skills) # its with word set, because with just (), you might consider its as tuple.
skills.add("Java")
print(skills)
update()
skills.update(["C++", "Go"])
remove()
skills.remove("Java")
Raises error if absent.
discard()
skills.discard("Java")
Safe version.
pop()
Removes random element.
skills.pop()
clear()
skills.clear()
copy()
new_skills = skills.copy()
Set Operations
A = {1,2,3,4}
B = {3,4,5,6}
Union
A.union(B)
# or
A | B
Intersection
A.intersection(B)
# or
A & B
Difference
A.difference(B)
# or
A - B
Symmetric Difference
A.symmetric_difference(B)
# or
A ^ B
issubset()
{1,2}.issubset({1,2,3})
Output:
True
issuperset()
{1,2,3}.issuperset({1,2})
Output:
True
Common Errors
KeyError
skills.remove("Rust")
Output:
KeyError
Use:
skills.discard("Rust")
Unhashable Type
data = {[1,2], [3,4]}
Output:
TypeError
6. Collection Methods Cheat Sheet
List
append()
extend()
insert()
remove()
pop()
clear()
index()
count()
sort()
reverse()
copy()
Tuple
count()
index()
Dictionary
get()
keys()
values()
items()
update()
pop()
popitem()
clear()
copy()
setdefault()
Set
add()
update()
remove()
discard()
pop()
clear()
copy()
union()
intersection()
difference()
symmetric_difference()
issubset()
issuperset()
7. Comparison Table
| Feature | List | Tuple | Dictionary | Set |
|---|---|---|---|---|
| Ordered | ✅ | ✅ | ✅ | ❌ |
| Mutable | ✅ | ❌ | ✅ | ✅ |
| Duplicates | ✅ | ✅ | Keys ❌ | ❌ |
| Indexing | ✅ | ✅ | ❌ | ❌ |
| Key Lookup | ❌ | ❌ | ✅ | ❌ |
| Unique Values | ❌ | ❌ | Keys Only | ✅ |
8. Common Beginner Mistakes
Mistake 1
student = {}
Creates Dictionary, not Set.
Correct:
student = set()
Mistake 2
x = (5)
Creates integer.
Correct:
x = (5,)
Mistake 3
for i in range(len(numbers)+1):
print(numbers[i])
Produces:
IndexError
Mistake 4
a = [[0] * 3] * 3
Unexpected behavior due to shared references.
Better:
a = [[0 for _ in range(3)] for _ in range(3)]
9. Real-World Combined Example
student = {
"name": "Amit",
"marks": [85, 90, 88],
"location": (20.2961, 85.8245),
"skills": {"Python", "SQL"}
}
print(student["name"])
print(student["marks"])
print(student["location"])
print(student["skills"])
Uses: - Dictionary - List - Tuple - Set
Together in a single object.
10. Time Complexity Basics
| Operation | List | Tuple | Dictionary | Set |
|---|---|---|---|---|
| Access | O(1) | O(1) | O(1) | N/A |
| Search | O(n) | O(n) | O(1) Avg | O(1) Avg |
| Insert End | O(1) | N/A | O(1) | O(1) |
| Delete | O(n) | N/A | O(1) | O(1) |
11. Interview Questions
Basic
- Difference between List and Tuple?
- Difference between Set and List?
- Difference between Dictionary and List?
- Why are Set values unique?
- Why are Dictionary keys unique?
Intermediate
- What is tuple unpacking?
- What is a nested dictionary?
- Difference between remove() and pop()?
- Difference between remove() and discard()?
- Why is Tuple immutable?
Advanced
- Why must Dictionary keys be immutable?
- How does a Set remove duplicates?
- Average complexity of Dictionary lookup?
- Difference between shallow copy and deep copy?
- When should you use a Set instead of a List?
12. Homework
Beginner
Q1
Create a list of 5 favorite movies.
Tasks: - Print - Add movie - Remove movie - Sort movies
Q2
Create a tuple containing:
(day, month, year)
Print values separately.
Q3
Create a Book Dictionary:
{
"title": "...",
"author": "...",
"price": ...
}
Tasks: - Update price - Add publisher - Delete publisher
Q4
Convert:
["apple", "banana", "apple", "orange"]
into a Set.
Explain why duplicates disappeared.
Intermediate
Q5
Given:
marks = [78,88,95,67,84]
Find: - Sum - Average - Highest - Lowest
Q6
Employee Dictionary:
employee = {
"name": "John",
"salary": 50000
}
Increase salary by 10%.
Q7
Perform:
A = {1,2,3,4}
B = {3,4,5,6}
Find: - Union - Intersection - Difference - Symmetric Difference
Advanced
Q8
Student Database:
students = [
{"name": "Rahul", "marks": 80},
{"name": "Amit", "marks": 92},
{"name": "Priya", "marks": 88}
]
Find: - Topper - Average marks
Q9
Remove duplicates from:
[1,2,3,2,5,1,6,3]
Without using set().
Q10
Create Contact Book
Features: - Add Contact - Delete Contact - Update Contact - Search Contact
Q11
Create Word Frequency Counter using Dictionary.
Q12
Create Inventory System using Dictionary.
Q13
Find common elements between two lists using Sets.
Q14
Create nested Company Dictionary.
Print: - Departments - Employees - Employee count
Final Decision Guide
Need ordered and changeable data?
→ LIST
Need ordered but fixed data?
→ TUPLE
Need key-value mapping?
→ DICTIONARY
Need unique values and fast membership checks?
→ SET
Master these four collections thoroughly and you will be able to solve a large percentage of real-world Python programming problems.