🧠 Python Tricky Outputs — Test Your Knowledge! Can you guess the output of these three Python snippets? Let's find out! 👇 🔍 OUTPUTS: Snippet 1 → '['a', 'b', 'c', 'd', 'e', 'f,g,h']' Snippet 2 → '{2, 3}' Snippet 3 → '2' 🔍HOW IT WORKS: "Snippet 1 — split() with maxsplit=5" Step 1 → String: "a,b,c,d,e,f,g,h" Step 2 → Split by comma ',' Step 3 → maxsplit=5 means only split the first 5 times. Step 4 → Result has 6 items (5 splits + remainder) Split 1 → "a" Split 2 → "b" Split 3 → "c" Split 4 → "d" Split 5 → "e" Remainder → "f,g,h" (no more splitting) "Snippet 2 — Set Intersection (&)" Step 1 → {1, 2, 3} Step 2 → {2, 3, 4} Step 3 → & (ampersand) finds common elements. Step 4 → Common elements: 2 and 3 Step 5 → Result: {2, 3} "Snippet 3 — dict.get() with default" Step 1 → Dictionary d = {"a": 1} Step 2 → d.get("b", 2) Step 3 → "b" is NOT a key in the dictionary Step 4 → get() returns default value → 2 Step 5 → If the key existed, it would return the actual value ⚠️ EDGE CASES: "split() maxsplit" maxsplit=0 → No splitting → Entire string as one item maxsplit > number of commas → Splits all, extra maxsplit ignored Empty string → [''] "Set intersection" Empty set → {} No common elements → set() Same sets → Returns the set itself "dict.get()" Key exists → Returns actual value Key missing → Returns default No default provided → Returns None 📌 REAL-WORLD APPLICATIONS: "split() with maxsplit" → Parsing logs, CSV headers, first N fields only "Set intersection" → Finding common users, shared interests, mutual friends "dict.get()" → Safe dictionary access, avoiding KeyError, from defaults 💡 KEY CONCEPTS: • 'split(',', maxsplit)' → Maximum number of splits to perform • '&' operator → Set intersection (common elements) • 'dict.get(key, default)' → Returns default if key missing • No KeyError → Safer than dict[key] 📌 QUICK QUIZ — Test Yourself: # Q1: What's the output? print("one,two,three,four".split(',', 2)) # Q2: What's the output? print({5, 6, 7} & {6, 7, 8}) # Q3: What's the output? d = {"name": "Alice"} print(d.get("age", 25)) #Python #Coding #Programming #LearnPython #Developer #Tech #PythonTips #Dictionary #Sets #Strings #CodeQuiz #SplitMethod #SetOperations #GetMethod #Day76
Python Tricky Outputs: Snippets and Edge Cases
More Relevant Posts
-
🔎 Mastering f-Strings in Python #Day32 If you're learning Python, f-strings are something you’ll use almost every day. They make string formatting cleaner, faster, and much more readable. 🔹 What Are f-Strings? f-strings (formatted string literals) were introduced in Python 3.6 and provide a simple way to embed variables and expressions directly inside strings. You create them by placing f before the opening quotation marks. Syntax: f"Your text {variable_or_expression}" Example: name = "Ishu" age = 20 print(f"My name is {name} and I am {age} years old.") ✅ Output: My name is Ishu and I am 20 years old. 🔹 Why Use f-Strings? Before f-strings, we used: 1. % Formatting (Old Style) name = "Ishu" print("Hello %s" % name) 2. .format() Method print("Hello {}".format(name)) 3. f-Strings (Modern Way) ✅ print(f"Hello {name}") 💡Cleaner 💡Easier to read 💡Faster than older methods 💡Supports expressions directly 🔹 Inserting Variables product = "Laptop" price = 55000 print(f"The {product} costs ₹{price}") Output: The Laptop costs ₹55000 🔹 Using Expressions Inside f-Strings You can perform calculations directly inside {} a = 10 b = 5 print(f"Sum = {a+b}") print(f"Product = {a*b}") Output: Sum = 15 Product = 50 🔹 Calling Functions Inside f-Strings name = "ishu" print(f"Uppercase: {name.upper()}") Output: Uppercase: ISHU 🔹 Formatting Numbers Decimal Places pi = 3.14159265 print(f"{pi:.2f}") Output: 3.14 .2f → 2 decimal places. 🔹 Adding Commas to Large Numbers num = 1000000 print(f"{num:,}") Output: 1,000,000 🔹 Formatting Percentages score = 0.89 print(f"{score:.2%}") Output: 89.00% 🔹 Padding and Alignment Left Align print(f"{'Python':<10}") Right Align print(f"{'Python':>10}") Center Align print(f"{'Python':^10}") Useful for reports and tables. 🔹 Using Expressions with Conditions marks = 85 print(f"Result: {'Pass' if marks>=40 else 'Fail'}") Output: Result: Pass Yes — even conditional logic works 😎 🔹 Date Formatting with f-Strings from datetime import datetime today = datetime.now() print(f"{today:%d-%m-%Y}") Example output: 26-04-2026 🔹 Debugging with f-Strings (Awesome Feature) Python allows this: x = 10 y = 20 print(f"{x=}, {y=}") Output: x=10, y=20 Great for debugging 🛠️ 🔹 Escaping Curly Braces Need literal braces? print(f"{{Python}}") Output: {Python} Use double braces {{ }} 🔹 f-Strings with Dictionaries student = {"name":"Ishu","marks":95} print(f"{student['name']} scored {student['marks']}") Output: Ishu scored 95 🔹 f-Strings with Loops for i in range(1,4): print(f"Square of {i} is {i*i}") Output: Square of 1 is 1 Square of 2 is 4 Square of 3 is 9 🔹 Final Thoughts f-Strings are one of Python’s most elegant features. They make your code: ✔More readable ✔More powerful ✔More Pythonic ✔More professional #Python #DataAnalytics #PythonProgramming #DataAnalysis #DataAnalysts #PowerBI #Excel #CodeWithHarry #Tableau #SQL #Consistency #DataVisualization #DataCleaning #DataCollection #MicrosoftPowerBI #MicrosoftExcel #F_Strings
To view or add a comment, sign in
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ```
To view or add a comment, sign in
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ``` 💬 *Double Tap ❤️ for Part 4!*
To view or add a comment, sign in
-
AI-generated Python code often has a "shared state" problem. Do you know where it's hiding? 🐍🔍 When reviewing Python, "it runs without errors" is the lowest possible bar. Because of Python's unique semantics, code can look perfectly logical while hiding architectural landmines that only manifest after multiple executions. In my latest AI Code Review session, we focused on the three "silent killers" frequently found in AI-generated Python snippets: ⚠️ 1. The Shared State Trap (Mutable Default Arguments) The most common bug: def log_event(name, log=[]). In Python, that empty list [] is created once at definition time, not every time the function is called. Every call shares the same object, leading to data leakage between unrelated requests. The Anchor: Look for [] or {} in function signatures—it's a massive red flag. 👣 2. The Iterator Trap (Mutation During Iteration) Modifying a list while looping over it—like calling list.remove(x) inside a for x in list: loop—causes the iterator to skip elements as the list shifts under its feet. The code won't crash; it will just silently produce incomplete results. The Anchor: Always verify if a loop is modifying its own source. If it is, use a list comprehension instead. 🔗 3. Final-Value Closures (Late-Binding Variables) AI models love creating lists of functions in loops: lambda: print(i). But Python captures the variable name, not its value at creation time. The result? Every function in your list will print the last value of the loop. The Anchor: Binding loop variables requires capturing them via default arguments: lambda idx=i: print(idx). The AI Reviewer's Perspective: LLMs are excellent at syntax, but they frequently fall for these three semantic "gotchas." As a reviewer (especially in RLHF tasks), your value lies in catching these subtle logic failures that simple test cases might miss. What’s your most "hated" Python gotcha? 👇 #Python #SoftwareEngineering #CodeQuality #AICodeReview #BugHunting #ProgrammingTips #CleanCode #RLHF #PromptEngineering IntelliForge Learning
To view or add a comment, sign in
-
🔸 🔸 🔸 Classic example to address late-binding and closures in python This 4 line of code talks about multiple important concepts ↘️ Code: funcs = [] for i in range(3): funcs.append(lambda : i) print([f() for f in funcs]) 🤔 What do you think ❓ Will it give any result, will it error out of random ❓ 🟰 Well, this prints [2,2,2] over console The idea is to demystify why this code does what it does under the hood. Concepts ↘️ ➡️ Is lambda : i a valid syntax ? If yes, what does it denote It denotes a shorthand notation to define a function that does not accept any input parameters and returns a single value as output. What will lambda : i resolve to ❓ ↘️ def f(): return i ❓ What is the iterative statement doing 🟰 It simply creates a container in memory, denoted by i. Initializes i to 0 and keeps incrementing the value that the container referenced by i contains ➡️ i : 0 -> 1 -> 2 ❓What will the list funcs hold ➡️ It's important to note here, funcs is a list that appends lambda into it. ➡️ Since, lambda is nothing more than a function in python, the list holds function ✅ ❓ But, how can a list hold function and what does it mean ➡️ Python treats function as objects, and in programming objects are nothing more than a memory address. 🟰 So, the funcs list holds memory addresses that individually resolve to functions denoted by lambda ✅ ➡️ Another important pointer to note here , the list holds the memory reference to these functions, not the actual value returned by the function. ✅ ❓ Demistify [f() for f in funcs] 🟰 This is a list comprehension in python. ➡️ We are iterating over all thats contained in the list, referencing each element via local variable f Since, f refers to an in-memory function, f() will simply invoke the function call. ✅ ➡️ When i = 0: Invoke f(), the first function pointed to by the first element of the list funcs ❓ The interesting part Function call always creates a new individual scope in python. You can say it as a standalone local environment specific to that function call. So, for the first element in funcs f() -> invokes a function that returns i ❓ Where is i now ➡️ Well, i comes from the loop scope created earlier and is used in the enclosed scope lambda : i denoted by function. ❓ So , are we talking about a closure concept in python here ? ➡️ Yes, this is a closure as lambda is closing over the variable i which is defined in the outer scope, the outer scope is the loop scope. ❓ Another interesting thing to note here is : ➡️ i is defined over a single outer scope, so it is shared amongst all the functions contained in the list funcs. 🤔 Think of it as : We are evaluating each function in the list funcs, where each function simply returns i. 🟰 The value of i = 2, post loop iteration finished in range(3), and hence each of these function calls will return the value 2 i.e. value of the variable closed over by lambda. #python #closure #lambda #softwareengineering #dataengineering
To view or add a comment, sign in
-
✅ Python Interview Questions with Answers 🐍💻 1️⃣ Reverse a string without using [::-1] python def reverse_string(s): return ''.join(reversed(s)) print(reverse_string("hello")) # Output: "olleh" 2️⃣ Count frequency of elements in a list python from collections import Counter data = [1, 2, 2, 3, 3, 3] counts = Counter(data) print(counts) # Output: {3: 3, 2: 2, 1: 1} 3️⃣ Check if two strings are anagrams python def is_anagram(s1, s2): return sorted(s1) == sorted(s2) print(is_anagram("listen", "silent")) # Output: True 4️⃣ Find duplicates in a list python def find_duplicates(lst): return list(set([x for x in lst if lst.count(x) > 1])) print(find_duplicates([1, 2, 2, 3, 4, 4])) # Output: [2, 4] 5️⃣ Lambda function to square numbers in a list python nums = [1, 2, 3, 4] squared = list(map(lambda x: x**2, nums)) print(squared) # Output: [1, 4, 9, 16] 📍Stay connected with Ravi Kiran Chintakayala for more
To view or add a comment, sign in
-
UNLEASHED THE PYTHON!i 1.5,2,& three!!! Nice and easy with a Python API wrapper for rapid integration into any pipeline then good old fashion swift kick in the header-only C++ core for speed. STRIKE WITH AIM FIRST ; THEN SPEED!! NO MERCY!!! 7 of 14 copy and paste Ai Next Step: Testing for Accuracy * Before we move to the C++ speed optimization, we should verify the decimal drift. 1. The Python Test (Validation) This script runs a quick simulation of your geometric growth with the 1.5 ratio & the 1,681 reset point. | V python def cyclic_validation(base=123, ratio=1.5, limit=1681): state = float(base) print(f"--- Starting Validation (Base: {base}, Ratio: {ratio}, Limit: {limit}) ---") for i in range(1, 11): state = (state * ratio) % limit print(f"Iteration {i:2}: {state:>10.4f}") print("--- Test Complete: Logic remains within the 1,681 boundary ---") cyclic_validation() /\ || Test Results: * Expansion: You'll see the values climb (184.5, 276.75, 415.125...). * Safety: At iteration 7, the value hits 1401.0469 and then "wraps" back to 420.5703—proving the 1,681 limit successfully prevents the number from spiraling into infinity. * * 2. The C++ Speed Engine (Performance) * Now that the logic is proven, this C++ implementation uses a template-based header to maximize throughput. It is designed to be dropped into a data pipeline for "others" to use. * | * V * cpp #include <iostream> #include <iomanip> /** * Cyclic41 Speed Engine * Prioritizes raw throughput and bit-level precision. */ class Cyclic41Engine { private: double state; const double limit = 1681.0; const double anchor = 41.0; public: Cyclic41Engine(double seed = 123.0) : state(seed) {} // Inline for maximum speed in loops inline double grow(double ratio) { state = (state * ratio); // Optimized manual modulo for double-precision speed while (state >= limit) state -= limit; return state; } inline double get_key(double drift = 4.862) { return (state * drift) / anchor; } }; int main() { Cyclic41Engine engine; // Simulating a high-speed data stream of 1 million points for (int i = 0; i < 1000000; ++i) { engine.grow(1.5); } std::cout << "Final stabilized state after 1M iterations: " << engine.get_key() << std::endl; return 0; } * /\ * || Key Technical Advantages: * Inline Functions: The grow and get_keymethods are marked inline to eliminate function call overhead, allowing the CPU to process millions of iterations in milliseconds. * Stabilized Precision: By using state -= limit instead of the standard floating-point % operator, we maintain better precision over massive iteration counts. * Hybrid Ready: This C++ engine can be wrapped using pybind11 to make it accessible as a Python library while keeping this native speed 7 of 14
To view or add a comment, sign in
-
1: Everything is an object? In the world of Python, (an integer, a string, a list , or even a function) are all treated as an objects. This is what makes Python so flexible but introduces specific behaviors regarding memory management and data integrity that must be will known for each developer. 2: ID and type: Every object has 3 components: identity, type, and value. - Identity: The object's address in memory, it can be retrieved by using id() function. - Type: Defines what the object can do and what values could be hold. *a = [1, 2, 3] print(id(a)) print(type(a)) 3: Mutable Objects: Contents can be changed after they're created without changing their identity. E.x. lists, dictionaries, sets, and byte arrays. *l1 = [1, 2, 3] l2 = l1 l1.append(4) print(l2) 4: Immutable Objects: Once it is created, it can't be changed. If you try to modify it, Python create new object with a new identity. This includes integers, floats, strings, tuples, frozensets, and bytes. *s1 = "Holberton" s2 = s1 s1 = s1 + "school" print(s2) 5: why it matters? and how Python treats objects? The distinction between them dictates how Python manages memory. Python uses integer interning (pre-allocating small integers between -5 and 256) and string interning for performance. However, it is matter because aliasing (two variables pointing to the same object) can lead to bugs. Understanding this allows you to choose the right data structure. 6: Passing Arguments to Functions: "Call by Assignment." is a mechanism used by Python. When you pass an argument to a function, Python passes the reference to the object. - Mutable: If you pass a list to a function and modify it inside, the change persists outside because the function operated on the original memory address. - Immutable: If you pass a string and modify it inside, the function creates a local copy, leaving the original external variable untouched. *def increment(n, l): n += 1 l.append(1) val = 10 my_list = [10] increment(val, my_list) print(val) print(my_list) *: Indicates an examples. I didn't involve the output, you can try it!
To view or add a comment, sign in
-
-
Day 15/30 - for Loops in Python What is a for Loop? A for loop is used to iterate — to go through every item in a sequence one by one and execute a block of code for each item. Instead of writing the same code 10 times, you write it once and let the loop repeat it automatically. The loop stops when it has gone through every item. The Golden Rule: A for loop works on any iterable — any object Python can step through one item at a time. This includes lists, tuples, strings, dictionaries, sets, and ranges. Syntax Breakdown for item in iterable: item -> This is a temporary variable holding the current item on each loop , you name it anything in -> It's the keyword that connects the variable to the iterable , always required iterable → the collection being looped - list, tuple, string, range, dict, set 1. How It Works, Step by Step 2. Python looks at the iterable and picks the first item 3. It assigns that item to your loop variable 4. It runs the indented block of code using that item 5. It moves to the next item and repeats steps 2–3 6. When there are no more items, the loop ends automatically The range() Function The range() generates a sequence of numbers for looping. The stop value is always excluded: range(5) -> 0, 1, 2, 3, 4 range(2, 6) -> 2, 3, 4, 5 range(0, 10, 2) -> 0, 2, 4, 6, 8 range(10, 0, -1) -> 10, 9, 8 ... 1 What You Can Loop Over List → loops through each item String → loops through each character one by one Tuple → same as list — goes item by item Dictionary → loops through keys by default; use .items() for key and value Range → loops through a sequence of generated numbers Set → loops through unique items (order not guaranteed) Tip: Use a name that makes the code readable — for fruit in fruits, for name in names, for i in range(10). i is the convention for index-style loops. Key Learnings ☑ A for loop iterates through every item in a sequence — running the same block for each one ☑ range(start, stop, step) generates numbers .Stop is always excluded ☑ You can loop over lists, strings, tuples, dicts, sets, and ranges ☑ The loop variable is temporary , holds the current item on each pass ☑ Indentation matters , only the indented block runs inside the loop Why It Matters: Loops are what turn Python from a calculator into an automation tool. Processing 10,000 sales records, sending emails to every customer, checking every row in a database - all of it uses loops. Writing code once and letting it repeat is one of the most powerful ideas in programming. My Takeaway Before loops, I was writing the same thing over and over. Now I write it once and Python handles the rest. That's what automation actually means - not robots, just smart repetition. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
Three months ago, our agent cited Python 3.13 as the latest stable release in a research report. It was wrong — 3.12 was current at the time. The factcheck caught it. Corrected the report. That part isn't remarkable. Any review process would catch that. What happened next is the part that matters: the agent stored a lesson. Not the corrected fact — the lesson about the mistake itself. "Always verify version numbers against the official release page. Don't rely on training data for anything with a release cycle." Two weeks later, I asked it to research a completely different tool. The vector memory surfaced that lesson during pre-search. The agent went straight to the official changelog before writing a single sentence about version compatibility. Nobody told it to. It remembered why it had been wrong before. This is the self-improvement loop I've been building toward in this series. Previous posts covered the infrastructure — four memory types, four storage systems, routing, retrieval. This post is about what it enables: an agent that gets better without being retrained. The loop: 1. Agent produces output 2. Factcheck or human review finds an error 3. The correction gets saved — not just the right answer, but the lesson: what went wrong and how to avoid it 4. Next time, pre-search surfaces the lesson before the agent starts working The key word is "lesson." We don't store "Python 3.12 is correct." We store "version numbers from training data are unreliable — always check the source." One is a fact that expires. The other is a behavior that compounds. The same loop runs on human feedback. I told the agent: "Don't mock the database in integration tests." Instead of losing that correction after the session, the agent saved it with structure — what was corrected, why it was wrong, how to apply it in the future. That's a feedback memory. Next time it writes integration tests — in any project, any session — it retrieves the lesson and applies it. Over time, these accumulate into working knowledge about how to do the job correctly. Does it work? In the first 20 research sessions, the agent averaged 3.2 factcheck corrections per report. After 80+ sessions with the lesson loop: 0.8. Not zero. But the same category of mistake rarely happens twice. Version numbers, citation formats, API accuracy — each corrected once, stored as a lesson, applied going forward. No fine-tuning, no retraining. The model is the same. The memory layer is what improved. The deeper insight: the agent doesn't just store information. It stores lessons about how to handle information. Facts expire. Lessons compound. What's the most repeated mistake your agent makes — the one you keep correcting but it never sticks? #AIAgents #AgentArchitecture #SelfImprovingAI
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