🐍 Did you know that Python closures capture variables, not values? This behavior is called late binding and it can cause surprising results. Example: funcs = [] for i in range(3): funcs.append(lambda: i) # tricky line print([f() for f in funcs]) # [2, 2, 2] Why does this happen? All the lambdas keep a reference to the same variable i. When the loop finishes, i equals 2, so every function returns 2. 💡 We can fix this by forcing early binding using default arguments: funcs.append(lambda i=i: i) This creates a new local variable i for each lambda and stores the current value at definition time. #Python #Closures #ProgrammingTips #LearningInPublic #SoftwareEngineering
Python Closures Capture Variables, Not Values
More Relevant Posts
-
Diving Deeper into Python Strings! Until now, I was building strings in the old-school way: using + to concatenate and str() to convert numbers. It works… but it’s messy. Today, I explored a cleaner, more powerful approach: format(). Here’s what I learned: {} are placeholders for variables. .format() handles type conversions automatically, no more str() headaches! Named placeholders make strings readable and flexible, even if variable order changes. Format numbers, align text, and make outputs neat, perfect for prices, tables, logs, or debug messages. 💡 String formatting isn’t just cleaner syntax, it makes your code readable, maintainable, and professional. Once you get it, your logs and outputs will look polished! #Python #Coding #StringFormatting #CleanCode #LearnPython #ProgrammingTips
To view or add a comment, sign in
-
-
Two numbers. Same math. Different answers. 🤯 Copy code Python x = 10**100 y = 10**100 + 1 print(x == y) Output: False Python handles this without blinking. No overflow. No precision loss. Now watch this: Python a = 1e16 b = a + 1 print(a == b) Output: True At this scale, adding 1 changes nothing. The value is already beyond what a float can accurately represent. Integers in Python grow as large as memory allows. Floats live within fixed precision and range boundaries. Same language. Same operator. Very different realities. Next time a number behaves “strangely”, remember — it’s not a bug, it’s a boundary. #Python #DataScience #ProgrammingInsights #NumericalComputing #TechThoughts
To view or add a comment, sign in
-
How much memory does a text column in your #Python #Pandas data frame use? Check: df['x'].memory_usage() But this is likely a huge underestimate! It sums the pointer sizes, not the string sizes. Instead, say: df['x'].memory_usage(deep=True) Or: df.info(memory_usage='deep')
To view or add a comment, sign in
-
-
LeetCode #217 – Contains Duplicate | Python Solution Iterating through nums, each element is checked against a HashSet — if it already exists, return True immediately; otherwise, insert it and continue. No nested loops, no redundant comparisons — just a single pass with instant lookups. 💡 Key Takeaway: Trading space for time is a core algorithmic principle. A set eliminates the need for brute-force O(n²) comparisons by giving constant-time lookups. ⏱ Time: O(n) 💾 Space: O(n) #LeetCode #DataStructures #Python #HashSet #CodingInterview #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day-38 of #100DaysOfCode 🐍 Python Sorting Algorithm Challenge Today I implemented Selection Sort from scratch to sort a list of numbers provided by the user—without using any built-in sorting methods. 🔹 What is Selection Sort? Selection Sort repeatedly selects the smallest element from the unsorted portion of the list and places it at the correct position. 🔹 Concepts Practiced: ✔ Nested loops ✔ Minimum element selection logic ✔ Index tracking ✔ In-place swapping 🔹 Approach: Iterate through the list Find the minimum element in the remaining unsorted part Swap it with the current index Repeat until the list is fully sorted 🔹 Key Insight: Selection Sort has a time complexity of O(n²), making it useful for understanding sorting fundamentals rather than large datasets. Working through such algorithms builds strong foundational knowledge of sorting and array manipulation 💡 #Python #SelectionSort #SortingAlgorithms #CorePython #100DaysOfCode #Day38 #LearnPython #CodingPractice #PythonDeveloper
To view or add a comment, sign in
-
-
🐍 Day 22 — Functions in Python Day 22 of #python365ai 🧩 Functions group reusable code. Example: def greet(name): print("Hello", name) 📌 Why this matters: Functions improve readability and reduce repetition. 📘 Practice task: Write a function that adds two numbers. #python365ai #PythonFunctions #CleanCode #LearnPython
To view or add a comment, sign in
-
-
Strings are everywhere in Python, and mastering string methods makes your code cleaner, faster, and more efficient. This visual covers commonly used Python string methods like: Case conversion (upper(), lower(), title()) Searching & counting (find(), index(), count()) Validation checks (isdigit(), isalpha(), islower()) Formatting & alignment (format(), center(), ljust(), rjust()) Cleaning & splitting (strip(), replace(), split()) These methods are extremely useful in Data Analytics, Data Cleaning, and Text Processing. #Python #DataAnalytics #PythonProgramming #LearningPython #DataScience #Coding #Developer #Analytics
To view or add a comment, sign in
-
-
By default, str.strip in #Python removes leading/trailing whitespace: s = ' a b c ' s.strip() # returns 'a b c' It takes an optional argument, naming leading/trailing characters to remove. Great for cleaning strings: s = '"Hello!"' s.strip(string.punctuation) # 'Hello'
To view or add a comment, sign in
-
-
Weekly Challenge 2: Sum Two Numbers Optimized. Yesterday I shared a Brute Force solution for the Two Sum problem. It worked, but it is slow(O(n^2)). Today, let's optimize it using a Hash Map. The strategy, instead of using nest loops to compare wverything against everything, we use memory to our advantage. As we iterate through the list, we calculate the "complement" (Target- Current) and ask "Have I seen this number before?" A highly efficient Python implementation of the 'Two Sum' problem using a Hash Map (Dictionary). Unlike the Brute Force approach, this script solves the problem in a single pass ($O(n)$) by storing visited numbers and checking for their complement instantly. Check the code on my GitHub: https://lnkd.in/eq5cQvWT #python #Optimization #Algorithms #DataStructures #BigO
To view or add a comment, sign in
-
Headline: Stop writing loops to clean your data. 🛑 One of the most common tasks in Python is handling duplicate entries. While you could write a for-loop with a conditional check, there’s a much faster, more "Pythonic" way to do it: Sets. Sets are unordered collections of unique elements. By casting your list to a set, Python handles the heavy lifting of deduplication instantly. Why use this? ✅ Cleaner, more readable code. ✅ Better performance for large datasets. ✅ Built-in membership testing (O(1) complexity). How are you using Sets in your current workflow? Let’s discuss below! 👇 #PythonProgramming #Pyspiders #CodingTips #SoftwareDevelopment
To view or add a comment, sign in
-
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