What are Collections?
Collections are used to store multiple values in a single variable.
Python provides different collection types. In this lesson, we will learn:
List
Ordered and changeable collection.
Tuple
Ordered and unchangeable collection.
Set
Unordered collection of unique values.
1. Lists
A list is an ordered and changeable collection of items.
Lists are created using square brackets
[].
fruits = ["Apple", "Banana", "Mango"] print(fruits)
['Apple', 'Banana', 'Mango']
Accessing List Items
fruits = ["Apple", "Banana", "Mango"] print(fruits[0]) print(fruits[2])
Apple Mango
2. List Methods
Python provides several methods for modifying lists.
append() Add an item remove() Remove an item pop() Remove an item by position sort() Sort the list
Example
numbers = [3, 1, 4] numbers.append(5) numbers.sort() print(numbers)
[1, 3, 4, 5]
3. Tuples
A tuple is an ordered collection that cannot be changed after creation.
Tuples are created using parentheses
().
colors = ("Red", "Green", "Blue")
print(colors)
print(colors[0])
('Red', 'Green', 'Blue')
Red
Lists are changeable, but tuples are unchangeable.
4. Sets
A set is an unordered collection of unique values.
Sets are created using curly brackets
{}.
numbers = {1, 2, 3, 3, 4}
print(numbers)
{1, 2, 3, 4}
Duplicate values are automatically removed from a set.
5. List vs Tuple vs Set
List → Ordered, Changeable, Allows duplicates Tuple → Ordered, Unchangeable, Allows duplicates Set → Unordered, Changeable, No duplicates
[] → List
() → Tuple
{} → Set
6. Practical Example
We can use a list to store the marks of a student.
marks = [80, 75, 90, 85, 88]
total = sum(marks)
print("Total Marks =", total)
print("Highest Marks =", max(marks))
Total Marks = 418 Highest Marks = 90
Use a List when you need a changeable collection.
Use a Tuple when the data should not be changed.
Use a Set when you need unique values.
Quick Quiz
Which collection does not allow duplicate values?
Finished this lesson?