Pythonic Dev
678 subscribers
103 photos
1 video
25 links
Happy Coding 💫
ADMIN: @cmatrix1
Download Telegram
🐍 Python Tip: Understanding len and getitem 📚

Greetings, Python enthusiasts! Today, let's explore two special methods in Python that are often used when working with custom objects or classes: __len__ and __getitem__.

1️⃣ __len__: This method allows us to define the behavior of the built-in len() function when applied to an instance of our class. By implementing __len__, we can specify how many elements or items our object contains. It provides a convenient way to retrieve the length of our custom objects.

2️⃣ __getitem__: This method enables us to implement indexing and slicing behavior for our objects. It allows us to access elements using square brackets (`[]`) and supports both single-item access and slicing. By implementing __getitem__, we can make our objects behave like built-in sequences such as lists or tuples.

These two methods, __len__ and __getitem__, provide powerful ways to customize the behavior of our objects and make them more intuitive to work with. They allow us to create classes that mimic the functionality of built-in data structures, providing a consistent and familiar interface to users.

By understanding and utilizing these methods effectively, we can enhance the usability and versatility of our custom classes. So, keep them in mind when designing your own Python objects!

Happy coding! 🚀💻

#Python
@Pythonic_Dev
👍1
📢 Exercise: Implement a Custom Immutable Sequence 🧩

Write a Python class that represents a custom immutable sequence. The sequence should follow an arithmetic pattern, where each term obtained by multiplying the position number (n) by 3 and then subtracting 1. 🔢

The class should have the following properties and methods:

Properties:
- length: An integer representing the length of the sequence. 📏

Methods:
- init(self, length): Initializes the sequence with the specified length. 🎯
- len(self): Returns the length of the sequence. 🔢
- getitem(self, index): Returns the value at the given index in the sequence. 📌

Your task is to implement the CustomSequence class according to the specifications provided above. Test your implementation with different lengths and verify that the sequence follows the desired arithmetic pattern.

#Python
@Pythonic_Dev
🐍 Python Tip: Understanding Concatenation and In-Place Operations 🧩


1️⃣ Concatenation:
operator (+) is used to concatenate strings, lists, tuples, or any other sequence types.

2️⃣ In-Place Concatenation:
modifies the original object itself instead of creating a new one. (+=)

3️⃣ In-Place Repetition:
It allows you to repeat an object multiple times and modify it in place.

🔒 Behavior in Mutable and Immutable Objects:
The behavior of concatenation and in-place operations differs between mutable and immutable objects. Immutable objects, such as strings and tuples, cannot be modified once created. Therefore, concatenation and in-place operations on immutable objects always create new objects.

On the other hand, mutable objects, such as lists, can modified. In-place operations directly modify the original object without creating a new one, making them more efficient for large data structures.

Happy coding! 🚀

#Python
@Pythonic_Dev
Internal Working of the len() Function in Python

🔍 The len() function in Python has a very peculiar characteristic that one had often wondered about. It takes absolutely no time, and equal time, in calculating the lengths of iterable data structures (string, array, tuple, etc.), irrespective of the size or type of data. This obviously implies O(1) time complexity. But have you wondered How?

🐍 Python follows the idea that keeping the length as an attribute is cheap and easy to maintain. len() is actually a function that calls the method 'len()'. This method is defined the predefined classes of iterable data structures. This method actually acts as a counter, that is automatically incremented as the data is defined and stored. Thus when you call the len() function, you do not give the interpreter the command to find the length by traversing, but rather you ask the interpreter to print a value that is already stored. Hence, len() function in Python runs in O(1) complexity.

⚠️ Note: This might seem very beneficial, but remember that it puts a remarkable burden the interpreter during the data definition phase. This is one of the many reasons why Python is slower during competitive programming, especially with big inputs.



Source : https://www.geeksforgeeks.org/internal-working-of-the-len-function-in-python/


#python
@Pythonic_Dev
In Python, the len() method for both lists and strings has a time complexity of O(1), which means it takes constant time to determine the length of a list or string regardless of its size.

The reason for this is that Python internally stores the length of lists and strings, so retrieving the length does not require iterating over the entire data structure. Instead, it simply returns the precomputed length value, resulting in constant time complexity.

#python
@Pythonic_Dev
📢 Hey Pythonistas! Today, let's dive into the fascinating world of mutable sequences and explore how we can manipulate data using slices. 🚀

Mutable sequences in Python, such as lists, allow us to modify their contents after creation. Slicing is a powerful technique that enables us to extract, insert, delete, and change elements within these sequences. Let's take a closer look at each operation:

1️⃣ Inserting Data:
To insert new elements into a mutable sequence using slices, we can leverage the slice assignment syntax.

2️⃣ Deleting Data:
Deleting elements from a mutable sequence using slices also
straightforward. We can utilize the same slice assignment syntax, but
assign an empty list ([]) to the desired slice.

3️⃣ Changing Data:
To modify existing elements within a mutable sequence using slices, we can directly assign new values to the desired slice.


Happy coding! 🐍💻
🔥1
🔥2
😁2
Exercise: CustomMutableString in Python 🔧

Implement a class called CustomMutableString that represents a mutable string. The class should have the following methods in second photo

Note: Make sure to handle appropriate type checking and raise any necessary exceptions when required.
Happy coding! 🐍💻

#Exercise
#python
@Pythonic_Dev
👍1
📢 Answer to the Exercise: CustomMutableString in Python! 🐍💻

Great job, everyone! It's time to reveal the solution to the exercise on implementing a CustomMutableString class. Here's the correct code:


Remember, coding challenges like these are crucial for enhancing your coding abilities. Stay tuned for more exciting exercises and programming insights. Happy coding, Pythonistas! 🚀🐍💻


#ExerciseAnswer
#python
@Pythonic_Dev
📢 Comprehensions Demystified! 💡

Hello fellow Python enthusiasts! Today, let's dive deep into the fascinating world of comprehensions in Python. Comprehensions are powerful constructs that allow us to generate lists (and other iterables) by transforming and filtering another iterable, all in a concise and elegant manner. So, let's unravel the internals of comprehensions and understand how they work.

Comprehension Internals:
Comprehensions have their own local scope, just like a function. When we encounter a comprehension, we should think of it as being wrapped in a function that is created by Python. This function will be executed to return the new list when the comprehension is evaluated.

1️⃣ Compilation Stage:
During the compilation stage, when the right-hand side (RHS) of the comprehension is compiled, Python creates a temporary function. This temporary function is responsible for evaluating the comprehension.

2️⃣ Execution Stage:
When the line containing the comprehension is executed, the following steps occur:

The temporary function is executed.
The returned object (the list) is stored in memory.
The name or variable on the left-hand side of the assignment is bound to that object.

Comprehension Scopes:
It's essential to understand that comprehensions are essentially functions and have their own local scope. However, they can also access global variables and nonlocal variables if needed.
Happy Coding 🐍

#Python
#Comprehensions
@Pythonic_Dev
👍1
As you can see, in step 4, Python created a function (MAKE_FUNCTION), called it (CALL_FUNCTION), and then returned the result (RETURN_VALUE) in the last step.

So, comprehensions will behave like functions in terms of scope. They have local scope, and can access global and nonlocal scopes too. And nested comprehensions will also behave like nested functions and closures.

#Python
#Comprehensions
@Pythonic_Dev
What is the output of Print?
Anonymous Quiz
43%
5
17%
6
7%
None
33%
NameError
2
What is the output of Prints?
Anonymous Quiz
47%
100000, 100000, 100000, 100000
22%
1, 10, 100, 1000
32%
Error
3👍2👎1
📢 Hey Pythonistas! Let's dive into a powerful and often underutilized feature in Python called init_subclass.

What is init_subclass?
init_subclass is a special method in Python that allows you to customize the behavior of class creation. It gets called automatically when a subclass is created, giving you the opportunity to perform custom initialization or enforce certain rules for subclasses.

🔧 How to use init_subclass?
To leverage this feature, define the init_subclass method within your base class. It takes two arguments: cls (representing the subclass) and any additional arguments you want to pass when creating the subclass.

🌟 Conclusion:
By leveraging init_subclass, you can easily apply common behaviors, rules, or validations to all subclasses of a base class. It's a powerful tool in your Python toolbox that can save you time and effort while ensuring consistency across your codebase.

Happy coding!

#OOP
#Python
👍2🤣1