This is a post about interesting behavour of "del" in Python. Do you think that "del x" calls x.__del__()? Well... >>> class Foo: ... def __del__(self): ... print("Deleting") >>> bar = Foo() >>> baz = bar >>> del bar Nothing is printed. Why? Now try >>> del baz Deleting The problem here is that bar and baz are the same object, and what "del" does is - removes the name (done) - decrements reference count for object (done, after "del bar" it is 1, baz still refers to the same object) - calls __del__, *if reference count is 0* (NOT done after "del bar", as the reference count is 1) When "del baz" is called, reference count finally reaches 0, and __del__ is called. While this kinda makes sense, it can be surprising and non-intuitive, if you don't really understand what is happening behind the scene. #python #gotcha
Alexey Vyskubov’s Post
More Relevant Posts
-
Python Empty Collections — Common Mistake [] # List () # Tuple {} # Dictionary (NOT a set) set() # Set Trick to Remember: 👉 {} = key:value → dictionary 👉 set() = only way to make empty set Example type({}) # dict type(set()) # set If you remember just this: “Curly braces empty = dict, not set” You’ll never make this mistake again. Source: https://lnkd.in/d8sbr7gc #Python
To view or add a comment, sign in
-
✅ Python: 04 🎯 Nested loops Let's share an interesting concept of python. we've this concept called nested loop, here we can use one loop inside of an another loop. We can get some interesting results. Let's take a look- for x in range(2): # outer loop for y in range(3): # inner loop print(f"({x} , {y})") # for co-ordinates 📌Code explanation: The outer loop will be executed 2 times & the inner loop will be executed 3 times, To begin with, the python interpreter will execute the outer loop first then it'll go to the inner loop and execute codes as follows, then it'll print as commanded and then jumps into the outer loop again, this will continue as per the range mentioned in the code. That's how nested loop works. #PythonProgramming #PythonDeveloper #Coding #python #nestedloopinpython #DataScience #pythondeveloper
To view or add a comment, sign in
-
-
If you work with Python, have you ever wondered: • What are magic methods? • Are they the same as special methods? • What about “dunder methods”? First thing is, magic methods are not really magic.They are just special methods defined by the Python Data Model. And, guess what, magic methods, special methods and dunder methods are all the same thing. Amazing, right? Let’s look at a simple example: 𝗰𝗹𝗮𝘀𝘀 𝗠𝘆𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻: 𝗱𝗲𝗳 __𝗹𝗲𝗻__(𝘀𝗲𝗹𝗳): 𝗿𝗲𝘁𝘂𝗿𝗻 𝟰𝟮 Now, when you call: 𝗹𝗲𝗻(𝗼𝗯𝗷) You’re NOT calling your method directly, Python is. This is the key insight and it is very important as we are going to see on another post. Takeaway: “Magic methods” are not magic. They are contracts with the Python interpreter. Implementing such methods are going to open a lot of new doors and it is a very pythonic whay of implementing your code. #python #magicmethods #dundermethods #specialmethods
To view or add a comment, sign in
-
Can You Spot the Problem in This Python Code? ☺️ At first glance, this code looks completely fine: def add_item(item, my_list=[]): my_list.append(item) return my_list print(add_item(1)) print(add_item(2)) print(add_item(3)) What do you expect the output to be? [1] [2] [3] But the actual output is: [1] [1, 2] [1, 2, 3] This is a classic Python pitfall: 😉 Default mutable arguments my_list=[] is created once at function definition time The same list is reused across function calls Each call keeps modifying the same object 😉 Why this matters 📌 This kind of bug: does NOT throw errors is hard to detect can silently affect logic So Correct approach 🔑 def add_item(item, my_list=None): if my_list is None: my_list = [] my_list.append(item) return my_list Never use mutable objects as default arguments in Python.
To view or add a comment, sign in
-
Stop using + to join strings in Python! 🐍 When you are first learning Python, it is tempting to use the + operator to build strings. It looks like this: name = "Gemini" status = "coding" print("Hello, " + name + " is currently " + status + ".") The Problem? In Python, strings are immutable. Every time you use +, Python has to create a brand-new string in memory. If you are doing this inside a big loop, your code will slow down significantly. The Pro Way: f-strings (Fast & Clean) Since Python 3.6, f-strings are the gold standard. They are faster, more readable, and handle data types automatically. The 'Pro' way: print(f"Hello, {name} is currently {status}.") Why use f-strings? Speed: They are evaluated at runtime rather than constant concatenation. Readability: No more messy quotes and plus signs. Power: You can even run simple math or functions inside the curly braces: print(f"Next year is {2026 + 1}") Small changes in your syntax lead to big gains in performance. Are you still using + or have you made the switch to f-strings? Let’s talk Python tips in the comments! 👇 #Python #CodingTips #DataEngineering #SoftwareDevelopment #CleanCode #PythonProgramming
To view or add a comment, sign in
-
Python Lists vs Tuples (Mutable vs Immutable) Lists = Mutable (can change) list_1 = ['apple', 'banana', 'orange', 'grape', 'mango'] list_2 = list_1 print(list_1) print(list_2) list_1[0] = 'Watermelon' print(list_1) print(list_2) Output: Both lists change (same reference in memory) --- Tuples = Immutable (cannot change) tuple_1 = ('apple', 'banana', 'orange', 'grape', 'mango') tuple_2 = tuple_1 print(tuple_1) print(tuple_2) # This will cause error tuple_1[0] = 'Watermelon' Error: TypeError: 'tuple' object does not support item assignment Key Insights: List → change allowed Tuple → change not allowed Both allow duplicates Both are ordered #Python
To view or add a comment, sign in
-
Python: sort() vs sorted() Have you ever had to pause for a second and think: “Do I need sort() or sorted() here?” 😅 This is the common Python confusions. Let’s clear it up. 🔹 list.sort() ◾ A method (belongs to list objects) ◾ Works only on lists ◾ Sorts the list in-place ◾ Changes the original list ◾ Returns None Example: numbers = [3, 1, 4, 2] numbers.sort() print(numbers) # [1, 2, 3, 4] 🔹 sorted() ◾ A function (built-in Python function) ◾ Returns a new sorted list ◾ Does NOT change the original ◾ Works on any iterable Example: numbers = [3, 1, 4, 2] new_numbers = sorted(numbers) print(new_numbers) # [1, 2, 3, 4] print(numbers) # [3, 1, 4, 2] The key difference: sort() → changes your original data sorted() → keeps your original data safe 💡 Quick way to remember: 👉 If you want to keep the original, use sorted() 👉 If you want to modify the list directly, use sort() #Python #Programming #LearnPython #DataScience #LearningJourney #WomenInTech
To view or add a comment, sign in
-
-
Ever wondered how to fetch the maximum and minimum values from a dictionary in Python without explicitly using a for loop? Assume you have a dictionary called bids of type `dict(str, int)`: `Maximum value` max_bid_user = max(bids, key=bids.get) max_bid_price = bids[max_bid_user] print(f"Highest Bid: {max_bid_user} with price: {max_bid_price}") `Minimum value` min_bid_user = min(bids, key=bids.get) min_bid_price = bids[min_bid_user] print(f"Lowest Bid: {min_bid_user} with price: {min_bid_price}") The max and min functions allow you to pass a key parameter, which in this case is bids.get. This tells Python to evaluate dictionary keys based on their corresponding values, making it easy to retrieve the keys with the highest and lowest values. #Python #AIML #AIwithAnishArya
To view or add a comment, sign in
-
Python Strings & Formatting String Formatting f-strings (Python 3.6+, recommended – cleanest): print(f"My name is {name} and I am {age}") # My name is Joy and I am 30 print(f"Next year, I will be {age + 1}") # Next year, I will be 31 String Methods phrase = "Hello World" print(phrase.lower()) # hello world print(phrase.upper()) # HELLO WORLD print(phrase.count('l')) # 3 print(phrase.find('World')) # 6 print(phrase.replace('World', 'Universe')) # Hello Universe Key Takeaways: - Multiple ways to format strings - f-strings = cleanest & recommended - Strings are immutable - .find() gives index, .count() counts chars #Python
To view or add a comment, sign in
-
-
Python : 03 🎯String operation: formatting string Here we'll be introduced how we can combine strings from the variable using formatting string. Let's take a look- variable1 = a variable2 = b lets call a variable called 'combined string' combined_string = f"{a} {b}" [💡# Here "f" stands for 'formatting'] print(combined_string) Result: a b [ 💡 Note: In Python (and most programming languages), quotes are the "boundary" that tells the computer: "Do not process this; just treat it as plain text. "When you omit the quotes, Python looks for a variable with that name. It goes to the memory location where combined_string is stored and grabs the value.] So, that is called a formatted string! ✅ This is the modern and most efficient way to format strings in Python. It evaluates the expressions inside the curly braces and converts them to text. Make sure you follow this account for more! #python #CodingCommunity #PythonDeveloper #coding #TechCommunity #Developers #pythonprogramming
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development