๐ Phase 1: Programming Fundamentals
๐ Topic 7: Python Data Structures (Lists, Tuples, Sets & Dictionaries)
Welcome back! ๐
So far, you've learned variables, operators, input/output, conditional statements, loops, and functions. Now it's time to learn one of the most important topics in Pythonโ Data Structures.
Data structures help us store, organize, and manage data efficiently. In Data Science, almost every dataset you work with will be stored or manipulated using these structures.
Python provides four built-in data structures:
โข List
โข Tuple
โข Set
โข Dictionary
Let's understand each one in detail.
๐น 1. List
A List is an ordered, mutable collection that allows duplicate values.
Creating a List
fruits = ["Apple", "Banana", "Mango"]
print(fruits)
Output
['Apple', 'Banana', 'Mango']
Accessing Elements
print(fruits[0])
print(fruits[2])
Output
Apple
Mango
Modifying a List
fruits[1] = "Orange"
print(fruits)
Output
['Apple', 'Orange', 'Mango']
Adding Elements
fruits.append("Grapes")
print(fruits)Removing Elements
fruits.remove("Orange")
print(fruits)๐น 2. Tuple
A Tuple is an ordered collection that cannot be modified after creation (immutable).
Creating a Tuple
colors = ("Red", "Green", "Blue")
print(colors)Accessing Elements
print(colors[1])
Output
Green
Why Use Tuples?
Use tuples when your data should never change.
Examples:
โข Months of the year
โข Days of the week
โข Fixed coordinates
๐น 3. Set
A Set is an unordered collection of unique elements.
Duplicate values are automatically removed.
Creating a Set
numbers = {1, 2, 2, 3, 4, 4, 5}
print(numbers)Output
{1, 2, 3, 4, 5}Adding Elements
numbers.add(6)
Removing Elements
numbers.remove(3)
Common Uses
โข Remove duplicates
โข Membership testing
โข Mathematical set operations
๐น 4. Dictionary โญ
A Dictionary stores data as key-value pairs.
It is one of the most frequently used data structures in Data Science.
Creating a Dictionary
student = {
"name": "Deepak",
"age": 24,
"course": "Data Science"
}
print(student)Accessing Values
print(student["name"])
Output
Deepak
Adding a New Key
student["city"] = "Mumbai"
Updating a Value
student["age"] = 25
Removing a Key
del student["course"]
๐น 5. Comparison of Data Structures
Feature | List | Tuple | Set | Dictionary
Ordered | โ | โ | โ | โ
Mutable | โ | โ | โ | โ
Duplicates Allowed | โ | โ | โ | Keys โ
Indexed | โ | โ | โ | By Key
๐น 6. Common List Methods
numbers = [10, 20, 30]
numbers.append(40)
numbers.insert(1, 15)
numbers.remove(20)
numbers.sort()
print(numbers)
๐น 7. Common Dictionary Methods