6, Python Lists & Sets
6.1. Lists in Python
A list is an ordered, mutable (changeable) collection that can store
different data types.
6.1.1Creating a List
fruits = ["apple", "banana", "cherry"] numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, 3.14, True]
6.1.2List Indexing in Python
Indexing allows accessing elements in a list using their position.
A,Positive Indexing (Left to Right)
Starts from 0 (first item).
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherry
B,Negative Indexing (Right to Left)
Starts from -1 (last item).
print(fruits[-1]) # cherry
print(fruits[-2]) # banana
print(fruits[-3]) # apple
📌 Note: Accessing an invalid(index greater than the length of the list)
index causes an error (IndexError).
6.1.3 Common List Methods
Methods Descriptio Example
n
append(x) Adds x to Fruits.append(“orange”)
the end
insert(i,x) Inserts x Fruits.insert(1,”grape”)
at index i
Extend([“kiwi,”mango Adds Fruits.extend([“kiwi,”mang
”]) multiple o”])
items
Remove(x) Removes Fruits.remove(“banana”)
first
occurrenc
e of x
Pop() Removes Fruits.pop()
last
element
Index(x) Returns Fruits.index(“cherry”)
index of x
Count(x) Return Fruits.count(“apple”)
number of
x appears
in the list
Reverse() Reverses Fruits.reverse()
the list
Clear() Removes Fruits.clear()
all
elements
Len(list) Return Len(fruits)
number of
elements
list have
6.1.4 Example: Using List Methods
fruits = ["apple", "banana", "cherry"] fruits.append("orange") # ['apple',
'banana', 'cherry', 'orange']
fruits.insert(1, "grape") # ['apple', 'grape', 'banana', 'cherry', 'orange']
fruits.pop() # Removes 'orange'
print(fruits) # ['apple', 'grape', 'banana', 'cherry']
6. 2. Sets in Python
A set is an unordered(indexing can't be used), immutable
(unchangeable) collection that stores unique elements (no duplicates).
6.2.1 Creating a Set
numbers = {1, 2, 3, 4, 5} fruits = {"apple", "banana", "cherry"}
6.2.2 Common Set Methods
Method Description Example
Add(x) Adds x to the set Fruits.add(“orange”)
Remove(x) Removes x Fruits.remove(“banana”)
Pop() Removes random Fuits.pop()
element from the
set
Clear() Removes all Fruitsclear()
elements
Union(set2) Combine set1 to Set1.union(set2)
set2
Intersection(set2) Return common Set1.intersection(set2)
elements
Difference(set2) Return elements Set1.difference(set2)
that are found in
set1 but not set2
Issubset(set2) Check if all Set1.issubset(set2)
elements in set1 is
inside set 2
Issuperset(set2) Check if all Set1.issuprrset(set2)
elements in set2 is
inside set 1
6.2.3 Example: Using Set Methods
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1.add(6) # {1, 2, 3, 4, 5, 6}
set1.remove(2) # {1, 3, 4, 5, 6}
common = set1.intersection(set2)# {4, 5, 6}
all_items = set1.union(set2)# {1, 3, 4, 5, 6, 7, 8}
print(common, all_items)
Summary
✅ Use Lists when order matters, and you need indexing or duplicate
values.
✅ Use Sets when you need unique values and fast lookups (removing
duplicates, set operations).