๐ Mastering Python Data Structures & OOP Concepts! ๐
Welcome back, data enthusiasts! ๐ In this blog, we dive into Python's powerful Data Structures and Object-Oriented Programming (OOP) principles. Let's make coding fun and easy! ๐
1๏ธโฃ Lists: Your Go-To Container! ๐ฆ
Lists are like shopping bags ๐ where you can store items of any type!
# Creating a list of fruits ๐๐๐
fruits = ["apple", "banana", "grape"]
# Adding an item ๐
fruits.append("strawberry")
# Removing an item โ
fruits.remove("banana")
# Accessing items ๐ข
print(fruits[0]) # Output: apple
# Looping through the list ๐
for fruit in fruits:
print(fruit)
# List Comprehension ๐
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
# Nested List Comprehension ๐น
matrix = [[i * j for j in range(3)] for i in range(3)]
print(matrix) # Output: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
2๏ธโฃ Strings: Handling Text with Ease! โ๏ธ
Strings are sequences of characters, like sentences in your favorite book! ๐
# Creating a string ๐
greeting = "Hello, World!"
# Concatenation โ
full_greeting = greeting + " How are you?"
# Slicing ๐ช
print(greeting[0:5]) # Output: Hello
# Splitting a string ๐
words = greeting.split(", ")
print(words) # Output: ['Hello', 'World!']
# String Methods โจ
print(greeting.upper()) # Output: HELLO, WORLD!
print(greeting.lower()) # Output: hello, world!
# Replacing Text in a String ๐
text = "BRB, TTYL, LOL"
text = text.replace("BRB", "Be right back").replace("TTYL", "Talk to you later").replace("LOL", "Laughing out loud")
print(text) # Output: Be right back, Talk to you later, Laughing out loud
3๏ธโฃ Dictionaries: Key-Value Magic! ๐โจ
Dictionaries store data in key-value pairs, like a mini-database! ๐
# Creating a dictionary ๐
student = {"name": "John", "age": 21, "major": "Computer Science"}
# Accessing values ๐ต๏ธโโ๏ธ
print(student["name"]) # Output: John
# Adding a new key-value pair โ
student["GPA"] = 3.8
# Removing a key-value pair โ
del student["age"]
# Looping through dictionary ๐
for key, value in student.items():
print(f"{key}: {value}")
4๏ธโฃ Tuples: Immutable Friends! ๐
Tuples are like lists but immutable (cannot be changed). Perfect for fixed data! ๐ผ
# Creating a tuple ๐ฆ
coordinates = (10, 20)
# Accessing elements ๐ข
print(coordinates[0]) # Output: 10
# Unpacking tuple ๐
x, y = coordinates
print(x, y) # Output: 10 20
5๏ธโฃ Sets: Unique Collections! ๐
Sets store unique items and are great for removing duplicates! ๐ซ๐
# Creating a set ๐
numbers = {1, 2, 3, 4, 4, 5}
# Adding an item โ
numbers.add(6)
# Removing an item โ
numbers.remove(3)
# Set operations ๐
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union โ
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
# Intersection โ
print(set1 & set2) # Output: {3}
๐ก Bonus: Object-Oriented Programming (OOP) ๐งโ๐ป
OOP helps us structure code using classes and objects. Letโs explore key OOP concepts with examples! ๐
1. Inheritance ๐งถ
Inheritance allows a class to inherit properties from another class.
# Single Inheritance
class Father:
def parent_prop(self):
print("This is the fatherโs property")
class Son(Father):
def job(self):
print("Son has his own job property")
child_obj = Son()
child_obj.job() # Output: Son has his own job property
child_obj.parent_prop() # Output: This is the fatherโs property
2. Method Overriding ๐
Overriding means redefining a parent class method in a child class.
class Fruit:
def fruit_info(self):
print("Inside the parent class")
class Apple(Fruit):
def fruit_info(self):
print("Inside the child class")
apple_obj = Apple()
apple_obj.fruit_info() # Output: Inside the child class
3. Multiple Inheritance & The Diamond Problem ๐
Multiple inheritance allows a class to inherit from multiple parent classes.
class A:
def method(self):
print("Method from A")
class B(A):
def method(self):
print("Method from B")
class C(A):
def method(self):
print("Method from C")
class D(B, C):
pass
obj = D()
obj.method() # Output: Method from B (Python uses Method Resolution Order - MRO)
4. Multilevel Inheritance ๐น
Multilevel inheritance involves a chain of inheritance where a class inherits from a derived class.
class Grandfather:
def grandparent_prop(self):
print("This is the grandfatherโs property")
class Father(Grandfather):
def parent_prop(self):
print("This is the fatherโs property")
class Son(Father):
def child_prop(self):
print("This is the sonโs property")
obj = Son()
obj.grandparent_prop() # Output: This is the grandfatherโs property
obj.parent_prop() # Output: This is the fatherโs property
obj.child_prop() # Output: This is the sonโs property
5. Hybrid Inheritance ๐น
Hybrid inheritance is a combination of more than one type of inheritance.
class A:
def method_a(self):
print("Method from A")
class B(A):
def method_b(self):
print("Method from B")
class C(A):
def method_c(self):
print("Method from C")
class D(B, C):
def method_d(self):
print("Method from D")
obj = D()
obj.method_a() # Output: Method from A
obj.method_b() # Output: Method from B
obj.method_c() # Output: Method from C
obj.method_d() # Output: Method from D
6. Polymorphism ๐ช
Polymorphism means "many forms" โ the same method can behave differently depending on the object.
class Teacher:
def lec_info(self):
print("Lecture info from Teacherโs perspective")
class Student:
def lec_info(self):
print("Lecture info from Studentโs perspective")
for obj in [Teacher(), Student()]:
obj.lec_info()
7. Encapsulation & Data Hiding ๐
Encapsulation hides data and controls access to it.
class Student:
def __init__(self, name, degree):
self.name = name # Public
self.__degree = degree # Private
def show(self):
print(f"Name: {self.name}, Degree: {self.__degree}")
s1 = Student("Manav", "B.Tech")
s1.show()
8. Class & Static Methods ๐
Class methods work with the class itself, while static methods are utility functions.
class Student:
total_students = 0
def __init__(self, name):
self.name = name
Student.total_students += 1
@classmethod
def get_total_students(cls):
return cls.total_students
@staticmethod
def greet():
print("Welcome to the class!")
Student.greet()
print(Student.get_total_students())
9. Dunder (Magic) Methods โจ๐ฎ
Dunder methods (short for Double UNDERSCORE, like __init__
and __str__
) are special methods that give classes superpowers to behave like built-in types! ๐
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
# Dunder method to control how the object is printed ๐
def __str__(self):
return f"'{self.title}' by {self.author}"
# Dunder method to define the length of the object ๐ข
def __len__(self):
return len(self.title)
book1 = Book("1984", "George Orwell")
print(book1) # Output: '1984' by George Orwell
print(len(book1)) # Output: 4 (length of the title)
__init__
: Initializes object properties when you create an instance.__str__
: Defines how the object is displayed when printed.__len__
: Lets you uselen()
on your objects!
๐ Wrapping Up! ๐
Python's Data Structures and OOP are the building blocks for writing efficient and scalable code. ๐๏ธ Whether youโre managing data with lists and dictionaries or structuring your program with OOP, Python makes it fun and easy! ๐
Stay tuned for more tutorials, and donโt forget to practice! ๐ป๐ฅ
Happy Coding! ๐๐ฉโ๐ป๐จโ๐ป