๐Ÿ Mastering Python Data Structures & OOP Concepts! ๐Ÿš€

ยท

6 min read

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 use len() 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! ๐ŸŽ‰๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

ย