🐍 Python Practice day 5– Here are some problems I solved today: ✅ Find the frequency of elements in a list ✅ Convert a list into a tuple ✅ Find common elements between two sets ✅ Remove duplicates from a list using a set ✅ Find union and intersection of two sets ✅ Create a dictionary from two lists (keys and values) ✅ Count frequency of characters in a string using a dictionary ✅ Merge two dictionaries ----------------------------------Day ----------------- Find the frequency of elements in a list. try: list1=[1,11,1,22,11,1,33,4,5,66,77,66,4,5] frequency_count={} for i in list1: if i in frequency_count: frequency_count[i]=frequency_count[i]+1 else: frequency_count[i]=1 print(frequency_count) except ValueError: print("Error occured") ==Tuples, Sets, Dictionaries == Convert a list into a tuple. list1=[1,2,3,4] tuple1=tuple(list1) print(tuple1) Find common elements between two sets. set1={1,2,3,3,4,4} set2={1,2,4,7} print(set1.intersection(set2)) Remove duplicates from a list using set. list1=[11,11,1,1,1,1,2,3,3] set1=set(list1) print(set1) list1=[11,11,1,1,1,1,2,3,3] unique_list=[] for i in list1: if i not in unique_list: unique_list.append(i) print(unique_list) Find union and intersection of two sets. set1={1,2,3,4,} set2={4,5,6,7,1} union1=set1.union(set2) inter_sec=set1.intersection(set2) print(union1) print(inter_sec) Create dictionary from two lists (keys and values) keys1=[1,2,3,4,5,6,7,8,9] values1=[9,8,7,6,5,4,3,2,1] dict_1={} for i in range(len(keys1)): dict_1[keys1[i]]=values1[i] print(dict_1) # Create dictionary from two lists (keys and values) keys1=[1,2,3,4,5,6,7,8,9] values1=[9,8,7,6,5,4,3,2,1] dict_1=dict(zip(keys1,values1)) print(dict_1) Count frequency of characters in a string using dictionary. str1="DpkWtmVMwwids.MMpAMLPlz" dict1={} for i in str1: if i in dict1: dict1[i]=dict1[i]+1 else: dict1[i]=1 print(dict1) # Merge two dictionaries. dict1={"Name":"Deepak", "Subject":"DataScience" } dict2={ "Designation":"DataEngineer", "Salary":"Ye batein btayi ni jati" } dict1.update(dict2) print(dict1) Working through these problems again helped reinforce concepts like: • Iteration and loops • Dictionary operations • Set theory in Python • Clean and Pythonic approaches like zip() and built-in methods #Python #Learning #Programming #DataScienceJourney #CodingPractice
Python Practice: Frequency, Tuples, Sets, Dictionaries
More Relevant Posts
-
🔥 Part-1: Tuples in Python (Complete Guide) 🔥 Tuples are one of the most important data structures in Python — simple, fast, and immutable! Let’s break it down in an easy and practical way 👇 📌 What is a Tuple? 👉 An ordered, immutable collection 👉 Allows duplicate values 👉 Written using parentheses () Example: fruits = ("apple", "orange", "cherry", "apple") print(fruits) # Output: ('apple', 'orange', 'cherry', 'apple') ✨ Ways to Create Tuples 🔹 1. Using Parentheses fruits = ("apple", "orange", "cherry") 🔹 2. Without Parentheses (Tuple Packing) numbers = 1, 2, 3, 4 print(type(numbers)) # Output: <class 'tuple'> 🔹 3. Single Element Tuple (Important ⚠️) single_tuple = ("apple",) print(type(single_tuple)) # Output: <class 'tuple'> 👉 Without comma, it becomes a string! 🎯 Accessing Elements 🔹 Indexing colors = ("red", "green", "blue", "orange") print(colors[0]) # red print(colors[-1]) # orange 🔹 Slicing nums = (10, 20, 30, 40, 50) print(nums[1:4]) # (20, 30, 40) ⚙️ Tuple Operations 🔹 Concatenation (+) print((1, 2) + (3, 4)) # (1, 2, 3, 4) 🔹 Repetition (*) print(("apple",) * 3) # ('apple', 'apple', 'apple') 🔁 Iteration in Tuple 🔹 Using for loop colors = ("red", "green", "blue") for color in colors: print(color) 🔹 Using while loop fruits = ("apple", "mango", "cherry") i = 0 while i < len(fruits): print(fruits[i]) i += 1 🛠️ Useful Methods & Functions 🔹 count() nums = (1, 2, 3, 2, 2) print(nums.count(2)) # 3 🔹 index() colors = ("red", "green", "blue") print(colors.index("green")) # 1 🔹 sorted() (returns list) nums = (3, 1, 2) print(sorted(nums)) # [1, 2, 3] 🔹 Built-in Functions numbers = (10, 20, 30, 40) print(len(numbers)) # 4 print(sum(numbers)) # 100 print(min(numbers)) # 10 print(max(numbers)) # 40 🎁 Packing & Unpacking 🔹 Unpacking coordinates = (10, 20, 30) x, y, z = coordinates print(y) # 20 🔹 Packing a = "Madhav" b = 21 c = "Engineer" tuple_pack = (a, b, c) print(tuple_pack) # ('Madhav', 21, 'Engineer') 🚀 Key Takeaways ✔ Tuples are immutable (cannot change) ✔ Faster than lists ✔ Useful for fixed data & security ✔ Supports indexing, slicing & iteration 💬 Stay tuned for Part-2 (Advanced Tuple Concepts) #Python #PythonProgramming #DataStructures #CodingTutorial #DataScience #SoftwareDevelopment
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 27 --Lambda Functions in Python Lambda Functions are small, anonymous functions that can be written in a single line. They are useful when you need a quick function for a short period of time and don’t want to formally define it using def. 🔹 Basic Syntax lambda arguments: expression 🔹 Example add = lambda a, b: a + b print(add(5, 3)) Output: 8 Here, the lambda function takes two arguments and returns their sum. 🔹 Using Lambda with map() map()--->The map() function is used to apply a specific function to every item in an iterable such as a list, tuple, or set. It returns a map object, so we usually convert it to a list to see the result. MAP SYNTAX:-map(function, iterable) function → the function you want to apply iterable → the list, tuple, or other collection of items EXAMPLE : Using Lambda with map() numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) Output: [1, 4, 9, 16, 25] 🔹 Using Lambda with filter() FILTER()--->The filter() function is used to select elements from an iterable based on a condition. It returns only the elements that satisfy the condition. SYNTAX:-filter(function, iterable) function → a function that returns True or False iterable → the collection of items to filter EXAMPLE : Using Lambda with filter() numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) Output: [2, 4, 6] EXAMPLE : Using Lambda with sorted() numbers =[1,2,3,4,5,6] sorted(numbers, key=lambda x:-x)# [6, 5, 4, 3, 2, 1] Key Points *Lambda functions are anonymous functions. *They are written in a single expression. *Commonly used with functions like map(), filter(), and sorted(). *Useful for short, simple operations. Learning concepts like this helps me understand how Python can write clean and concise code. Do you prefer lambda or regular def functions? Drop your answer below 👇 #Python #PythonLearning #CodingJourney #Programming
To view or add a comment, sign in
-
-
🚀 I Learned Two Python Concepts Today That Instantly Made My Code Better Today I practiced two important Python concepts: • While Loops • Format Specifiers (Python f-string formatting) Both are heavily used in real programs for input validation and clean output formatting. 🔁 1. While Loop — Repeating Code Until a Condition Changes A while loop repeatedly executes code as long as a condition is true. age = int(input("Enter your age: ")) while age < 0: print("Age cannot be negative") age = int(input("Enter your age: ")) print(f"You are {age} years old") 📌 What Happens 1️⃣ User enters age. 2️⃣ If the value is negative, an error appears. 3️⃣ The program asks again until a valid value is entered. 🌍 Real‑world uses • Input validation • Login retry systems • Game loops • Menu programs For example, an ATM keeps asking for a PIN until it is correct. 🔄 2. Infinite Loop + Break (Common Pattern) while True: principal = float(input("Enter principal amount: ")) if principal < 0: print("Principal cannot be negative") else: break 🧠 Logic • while True creates a continuous loop • Invalid input → error message • Valid input → break stops the loop This pattern is widely used for reliable user input handling. 🎯 3. Format Specifiers — Clean Output Formatting Python f-strings allow precise formatting of numbers. General syntax {value:flags} Example value price = 3000.1459 🔢 Round to specific decimals print(f"{price:.2f}") Output 3000.15 .2f → round to 2 decimal places (very common in finance). 0️⃣ Zero padding / fixed width print(f"{price:010}") Example 0003000.1459 Useful for IDs, invoices, or structured tables. 📊 Number alignment Left {value:<10} Right {value:>10} Center {value:^10} Helpful when printing tables or reports. 💰 Sign and comma formatting print(f"{price:+,.2f}") Output +3,000.15 Meaning: • + show sign • , thousands separator • .2f two decimals Common in financial dashboards and reports. 🧮 Example: Compound Interest total = principal * pow((1 + rate/100), time) print(f"Balance after {time} years: ${total:.2f}") This demonstrates: • while-loop validation • calculation logic • formatted output 📚 What I Practiced Today • While loops • Infinite loop pattern • Input validation • Python format specifiers • Clean numeric output Programming is about controlling logic and handling real data correctly. 🔗 Code Repository GitHub: https://lnkd.in/dFtwyqEw #python #pythonlearning #codingjourney #programming #softwaredeveloper #learnpython #developers #100daysofcode #computerscience
To view or add a comment, sign in
-
-
⚡ How do loops affect performance and memory usage in Python? When working with large datasets, the way we write loops can affect both performance and memory usage. A loop simply repeats the same operation over multiple elements. As the dataset grows, the number of operations grows as well, so choosing the right approach becomes important. 🔹 Traditional loop vs List Comprehension Suppose we want to compute the square of numbers in a list. A traditional loop might look like this: numbers = [1,2,3,4,5] squares = [ ] for n in numbers: squares.append(n**2) This works fine, but each iteration performs several steps: 1️⃣ Access the element 2️⃣ Compute the value 3️⃣ Append it to the list Python offers a cleaner and often faster approach called List Comprehension: squares = [n**2 for n in numbers] ✅ Same result ✅ Shorter, more readable code ✅ Often faster due to internal optimizations 🔹 Nested loops and Time Complexity ⏱ Performance issues become more noticeable with nested loops: for i in range(n): for j in range(n): print(i, j) If the input size is n, the number of operations becomes: n × n 📊 Time Complexity = O(n²) This means execution time grows rapidly as the dataset increases. Example: • n = 10 → ~100 operations • n = 100 → ~10,000 operations • n = 1000 → ~1,000,000 operations ⚠️ That’s why nested loops can slow down programs when dealing with large datasets. 🔹 Using built-in functions instead of loops Sometimes we don’t need to write loops at all, since Python provides optimized built-in functions. Example: numbers = [1,2,3,4] total = sum(numbers) Other useful functions include: • map() → applies a function to every element: squares = list(map(lambda x: x**2, numbers)) • filter() → selects elements that satisfy a condition: even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) These approaches often produce cleaner and more expressive code. 🔹 Memory efficiency with Generators 💡 With very large datasets, memory usage becomes critical. numbers = [x for x in range(1000000)] This stores all values in memory. Using a generator instead: numbers = (x for x in range(1000000)) Values are generated one at a time during iteration, reducing memory usage. ➡️ This is especially useful when processing large data streams. 💡Python Performance Tips ✔ Use List Comprehensions for cleaner, faster loops ✔ Be careful with nested loops (O(n²)) ✔ Use built-in functions like sum(), map(), filter() ✔ Use generators for better memory efficiency Efficient code in Python is about choosing the right tool for the task. #Python #PythonProgramming #LearnPython #SoftwareEngineering #Coding
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
-
Lists in Python A versatile data structure used to store multiple items in a single variable. 🎯 1. What is a List? Lists are ordered, mutable collections of items that allow duplicate elements. They are defined using square brackets []. 🎯 2. Creating a List A list by placing comma-separated values inside square brackets. python # Example my_list = [1, "Hello", 3.14, True] 🎯 3. Accessing List Elements & Indexing zero-based indexing to access elements. python # Example fruits = ["apple", "banana", "cherry"] print(fruits[0]) # First element print(fruits[-1]) # Last element 🎯 4. List Slicing Access a range of elements Syntax [start:stop:step]. python # Example numbers = [10, 20, 30, 40, 50, 60] print(numbers[1:4]) # From index 1 up to (but not including) 4 print(numbers[::-1]) # Reverse the list Output: [20, 30, 40] [60, 50, 40, 30, 20, 10] 🎯 5. Modifying Lists Lists are mutable, meaning you can change their items. python # Example fruits = ["apple", "banana", "cherry"] fruits[1] = "blueberry" # Change index 1 print(fruits) Output: [apple, blueberry, cherry] 🎯 6. List Methods append() : Adds an item to the end. python fruits.append("orange") insert() : Adds an item at a specific position. python fruits.insert(1, "mango") remove() : Removes the first occurrence of a specific value. python fruits.remove("banana") pop() : Removes and returns an item at a specific index (or the last item if no index is specified). python last_item = fruits.pop() sort() : Sorts the list in place. 🎯 List Comprehensions A list comprehension offers a concise way to create lists in Python based on existing lists or iterables. Basic Syntax: new_list = [expression for item in iterable if condition] 🎯 1. Creating a List of Squares Instead of using a for loop to append squares, you can do it in one line. python # Traditional loop squares = [] for x in range(1, 6): squares.append(x*2) 🎯 List comprehension squares = [x*2 for x in range(1, 6)] print(squares) Output: [1, 4, 9, 16, 25] 🎯 2. Filtering with if Condition You can add a condition to filter elements from the original list. python numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Get only even numbers evens = [x for x in numbers if x % 2 == 0] print(evens) Output: [2, 4, 6, 8, 10] 🎯 3. Transforming Strings You can apply string methods like .upper() during creation. python fruits = ["apple", "banana", "cherry"] # Convert all to uppercase upper_fruits = [fruit.upper() for fruit in fruits] print(upper_fruits) Output: ['APPLE', 'BANANA', 'CHERRY'] 🎯 4. Flattening a Nested List This is a highly efficient way to turn a list of lists into a single flat list. python nested_list = [[1, 2], [3, 4], [5, 6]] # Flatten the list flatlist = [item for sublist in nestedlist for item in sublist] print(flat_list) Output: [1, 2, 3, 4, 5, 6] #PythonProgramming #PythonList #DataScience #CodingTips #PythonTutorial #SoftwareDevelopment #Programming
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
-
-
Python 3: Mutable, Immutable... Everything Is Object Python treats everything as an object. A variable is not a box that stores a value directly; it is a name bound to an object. That is why assignment, comparison, and updates can behave differently depending on the type of object involved. For example, a = 10; b = a means both names refer to the same integer object, while l1 = [1, 2]; l2 = l1 means both names refer to the same list object. Many Python surprises come from object identity and mutability. Two built-in functions are essential when studying objects: id() and type(). type() tells us the class of an object, while id() gives its identity in the current runtime. Example: a = 3; b = a; print(type(a)) prints <class 'int'>, and print(a is b) prints True because both names point to the same object. By contrast, l1 = [1, 2, 3]; l2 = [1, 2, 3] gives l1 == l2 as True but l1 is l2 as False. Equality checks value, but identity checks whether two names point to the exact same object. Mutable objects can be changed after they are created. Lists, dictionaries, and sets are common mutable types. If two variables reference the same mutable object, a change through one name is visible through the other. Example: l1 = [1, 2, 3]; l2 = l1; l1.append(4); print(l2) outputs [1, 2, 3, 4]. The list changed in place, and both names still point to that same list. Immutable objects cannot be changed after creation. Integers, strings, booleans, and tuples are common immutable types. If an immutable object seems to change, Python actually creates a new object and rebinds the variable. Example: a = 1; a = a + 1 does not modify the original 1; it creates 2 and binds a to it. The same happens with strings: s = "Hi"; s = s + "!" creates a new string. Tuples are also immutable: (1) is just the integer 1, while (1,) is a tuple. This matters because Python treats mutable and immutable objects differently during updates. l1.append(4) mutates a list in place, but l1 = l1 + [4] creates a new list and reassigns the name. With immutable objects, operations produce a new object rather than changing the existing one. That is why == is for value and is is for identity, especially checks like x is None. Arguments in Python are passed as object references. A function receives a reference to the same object, not a copy. That means behavior depends on whether the function mutates the object or simply rebinds a local name. Example: def add(x): x.append(4) changes the original list. But def inc(n): n += 1 does not change the caller’s integer because integers are immutable and the local variable is rebound. From the advanced tasks, I also learned that CPython may reuse some constant objects such as small integers and empty tuples as an optimization. That helps explain identity results, but it also reinforces the rule: never rely on is for value comparison when == is what you mean.
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