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
Understanding Python For Loops in 30 Days
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
-
🐍 30 Python Challenges to Test Your Skills! 💻 1️⃣ Reverse a string without using loops 🔄 2️⃣ Count duplicates in a list 📝 3️⃣ Flatten a nested list 📂 4️⃣ Find all prime numbers up to N 🔢 5️⃣ Check if a string is a palindrome 🔁 6️⃣ Swap two variables in Python ⚡ 7️⃣ Merge two dictionaries efficiently 🗂️ 8️⃣ Remove all vowels from a string ✂️ 9️⃣ Sort a list of dictionaries by a key 🔑 🔟 Generate Fibonacci numbers in one line 🔢 1️⃣1️⃣ Find the most common element in a list 📊 1️⃣2️⃣ Remove duplicates while preserving order ✅ 1️⃣3️⃣ Find largest & smallest number without min()/max() 🔝🔽 1️⃣4️⃣ Count character occurrences in a string 🔡 1️⃣5️⃣ Reverse words in a sentence 🔁 1️⃣6️⃣ Check if two strings are anagrams 🔤 1️⃣7️⃣ Check if a number is a perfect square ◼️ 1️⃣8️⃣ Transpose a 2D list (matrix) 🔄 1️⃣9️⃣ Convert a list of strings to integers, ignoring invalid inputs 🔢 2️⃣0️⃣ Filter even numbers from a list ✨ 2️⃣1️⃣ Calculate factorial using recursion or loops 🔁 2️⃣2️⃣ Check if a number is prime efficiently 🔢 2️⃣3️⃣ Generate all subsets of a list 📂 2️⃣4️⃣ Capitalize the first letter of each word ✍️ 2️⃣5️⃣ Merge two sorted lists into one sorted list 🗂️ 2️⃣6️⃣ Find second largest number in a list 🔝 2️⃣7️⃣ Count vowels in a string 🔡 2️⃣8️⃣ Check if a list is sorted ✅ 2️⃣9️⃣ Find indices of all occurrences of an element 📌 3️⃣0️⃣ Check if a string is a pangram 🔠 💡 Pro Tip: The most Pythonic solutions often use list comprehensions, sets, dictionaries, and built-in functions. ⚡ Try them out and comment your favorite solution! Don’t forget to share tips & tricks you use daily in Python. 🔁 Repost to help others learn faster ❤️ Like if you found it useful 📥 Save it for future reference 👥 Tag someone who needs this! #Python 🐍 #Programming 💻 #CodingChallenge 🚀 #Developers 👨💻 #TechInnovation 💡 #AI 🤖 #MachineLearning 🧠 #DataScience 📊 #Automation ⚡#SoftwareEngineering 💻 #ProgrammingLife 📝 #TechTrends 📈 #PythonTips 🐍 #LearnToCode 📚 #ProblemSolving 🧩 #DeveloperCommunity #TechSkills ⚡ #PythonProgramming 🐍
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
-
*Let's now understand the A–Z of Python programming concept in more detail:* *A - Arguments* Inputs passed to a function. They can be: - Positional: based on order - Keyword: specified by name - Default: pre-defined if not passed - Variable-length: *args, **kwargs for flexible input. *B - Built-in Functions* Predefined functions in Python like: print(), len(), type(), int(), input(), sum(), sorted(), etc. They simplify common tasks and are always available without import. *C - Comprehensions* Compact syntax for creating sequences: - List: [x*x for x in range(5)] - Set: {x*x for x in range(5)} - Dict: {x: x*x for x in range(5)} Efficient and Pythonic way to process collections. *D - Dictionaries* Key-value data structures: person = {"name": "Alice", "age": 30} - Fast lookup by key - Mutable and dynamic *E - Exceptions* Mechanism to handle errors: try: 1/0 except ZeroDivisionError: print("Can't divide by zero!") Improves robustness and debugging. *F - Functions* Reusable blocks of code defined using def: def greet(name): return f"Hello, {name}" Encapsulates logic, supports DRY principle. *G - Generators* Special functions using yield to return values one at a time: def countdown(n): while n > 0: yield n n -= 1 Memory-efficient for large sequences. *H - Higher-Order Functions* Functions that accept or return other functions: map(), filter(), reduce() Custom functions as arguments *I - Iterators* Objects you can iterate over: Must have '__iter__()' and '__next__()' Used in for loops, comprehensions, etc. *J - Join Method* Combines list elements into a string: ", ".join(["apple", "banana", "cherry"]) # Output: "apple, banana, cherry" *K - Keyword Arguments* Arguments passed as key=value pairs: def greet(name="Guest"): print(f"Hello, {name}") greet(name="Alice") Improves clarity and flexibility. *L - Lambda Functions* Anonymous functions: square = lambda x: x * x Used in short-term operations like sorting or filtering. *M - Modules* Files containing Python code: import math print(math.sqrt(16)) # 4.0 Encourages reuse and organization. *N - NoneType* Represents "no value": result = None if result is None: print("No result yet") *O - Object-Oriented Programming (OOP)* Programming paradigm with classes and objects: class Dog: def bark(self): print("Woof!") Supports inheritance, encapsulation, polymorphism. *P - PEP8 (Python Enhancement Proposal 8)* Python’s official style guide: - Naming conventions - Indentation (4 spaces) - Line length (≤ 79 chars) Promotes clean, readable code. *Q - Queue (Data Structure)* FIFO structure used for tasks: from collections import deque q = deque() q.append("task1") q.popleft() *R - Range Function* Used to generate a sequence of numbers: range(0, 5) # 0, 1, 2, 3, 4 Often used in loops.
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
-
🚀 Python Series – Day 15: Exception Handling (Handle Errors Like a Pro!) Yesterday, we learned how to work with files in Python 📂 Today, let’s learn how to handle errors smartly without crashing your program ⚠️ 🧠 What is Exception Handling? Exception handling is a way to manage runtime errors so your program continues running smoothly. 👉 Without it → program crashes ❌ 👉 With it → program handles error gracefully ✅ 💻 Understanding try and except try: # risky code (may cause error) except: # runs if error occurs 🔍 How it Works: ✔️ Python first executes code inside try ✔️ If NO error → except is skipped ✔️ If error occurs → Python jumps to except ⚡ Example 1 (Basic) try: num = int(input("Enter number: ")) print(10 / num) except: print("Something went wrong!") 👉 If user enters 0 or text, error is handled. 🔥 Why Avoid Only except? Using only except is not a good practice ❌ 👉 It hides the real error. ✅ Best Practice: Handle Specific Errors try: num = int(input("Enter number: ")) print(10 / num) except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Please enter a valid number!") ⚡ Multiple Exceptions in One Line except (ZeroDivisionError, ValueError): print("Error occurred!") 🧩 else Block (Less Known 🔥) try: num = int(input("Enter number: ")) except ValueError: print("Invalid input") else: print("No error, result:", num) 👉 else runs only if no error occurs 🔒 finally Block (Very Important) try: print("Trying...") except: print("Error") finally: print("This always runs ✅") 👉 Used for cleanup (closing files, database, etc.) 🎯 Why This is Important? ✔️ Prevents crashes ✔️ Makes programs professional ✔️ Used in real-world apps, APIs, ML projects ⚠️ Pro Tips: 👉 Always use specific exceptions 👉 Use finally for cleanup 👉 Don’t hide errors blindly 📌 Tomorrow: Modules & Packages (Organize Your Code Like a Pro) Follow me to master Python step-by-step 🚀 #Python #Coding #Programming #DataScience #LearnPython #100DaysOfCode #Tech #MustaqeemSiddiqui
To view or add a comment, sign in
-
-
------------------------------------------- Day 19 of My Python Learning Journey ------------------------------------------- ==> Functions in Python Today I explored one of the most powerful concepts in Python: Functions 🔥 🔹 What are Functions? Functions are reusable blocks of code that perform a specific task. They help us write cleaner and more efficient programs. 🔹 Why do we need Functions? ✔ Reduce code repetition ✔ Improve readability ✔ Break complex problems into smaller parts ✔ Promote code reusability 🔹 Advantages of Functions ✅ Reusability ✅ Easy debugging ✅ Better structure (modular programming) ✅ Saves time and effort 💡 How to Define a Function? def function_name(parameters): # code return value 🔹 Types of Functions 👉 Built-in Functions: print(), len(), sum() 👉 User-defined Functions: Created using def 🔹 Types of Arguments in Python ✔ Default Arguments def greet(name="Guest"): print("Hello", name) ✔ Positional Arguments def add(a, b): print(a + b) ✔ Keyword Arguments def student(name, age): print(name, age) ✔ Arbitrary Arguments 👉 *args (Multiple values → Tuple) def total(*numbers): print(sum(numbers)) 👉 **kwargs (Key-value pairs → Dictionary) def details(**info): print(info) 🔥 *args vs **kwargs *args → handles multiple positional arguments (tuple) **kwargs → handles multiple keyword arguments (dictionary) def demo(*args, **kwargs): print(args) print(kwargs) demo(1, 2, 3, name="Madhava", age=20) 📌 Key Takeaway: Functions make code reusable, organized, and efficient — a must-know for every developer! ------------------ Implementation ------------------ # Day 19 - Functions in Python # 1. Default Argument def greet(name="Guest"): print("Hello", name) # 2. Positional Arguments def add(a, b): print("Sum:", a + b) # 3. Keyword Arguments def student(name, age): print("Name:", name, "| Age:", age) # 4A. Arbitrary Positional Arguments (*args) def total(*numbers): sum_val = 0 for n in numbers: sum_val += n print("Total:", sum_val) # 4B. Arbitrary Keyword Arguments (**kwargs) def details(**info): print("Details:") for key, value in info.items(): print(key, ":", value) # 5. *args vs **kwargs together def demo(*args, **kwargs): print("Args:", args) print("Kwargs:", kwargs) # Function Calls greet() greet("Madhava") add(10, 20) student(age=20, name="Madhava") total(1, 2, 3, 4, 5) details(name="Madhava", age=20, dept="CSE") demo(1, 2, 3, name="Madhava", age=20)
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
-
-
Task Holberton Python: Mutable vs Immutable Objects During this trimester at Holberton, we started by learning the basics of the Python language. Then, as time went on, both the difficulty and our knowledge gradually increased. We also learned how to create and manipulate databases using SQL and NoSQL, what Server-Side Rendering is, how routing works, and many other things. This post will only show you a small part of everything we learned in Python during this trimester, as covering everything would be quite long. Enjoy your reading 🙂 Understanding how Python handles objects is essential for writing clean and predictable code. In Python, every value is an object with an identity (memory address), a type, and a value. Identity & Type x = 10 print(id(x)) print(type(x)) Mutable Objects Mutable objects (like lists, dicts, sets) can change without changing their identity. lst = [1, 2, 3] lst.append(4) print(lst) # [1, 2, 3, 4] Immutable Objects Immutable objects (like int, str, tuple) cannot be changed. Any modification creates a new object. x = 5 x = x + 1 # new object Why It Matters With mutable objects, changes affect all references: a = [1, 2] b = a b.append(3) print(a) # [1, 2, 3] With immutable objects, they don’t: a = "hi" b = a b += "!" print(a) # "hi" Function Arguments Python uses “pass by object reference”. Immutable example: def add_one(x): x += 1 n = 5 add_one(n) print(n) # 5 Mutable example: def add_item(lst): lst.append(4) l = [1, 2] add_item(l) print(l) # [1, 2, 4] Advanced Notes - Shallow vs deep copy matters for nested objects - Beware of aliasing: matrix = [[0]*3]*3 Conclusion Mutable objects can change in place, while immutable ones cannot. This impacts how Python handles variables, memory, and function arguments—key knowledge to avoid bugs.
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