💬 Discussion Question In Python, if we have a list called "lst1", there are multiple ways to sort the data. Two of the most common approaches are: 1️⃣ "lst1.sort()" 2️⃣ "sorted(lst1)" But what is the difference between them, and when should we use each one? 🔹 "lst1.sort()" - It is a list method. - It sorts the elements in-place, meaning it modifies the original list itself. - It does not return a new list (it returns "None"). Example: lst1 = [4, 2, 7, 1] lst1.sort() print(lst1) Output: [1, 2, 4, 7] 🔹 "sorted(lst1)" - It is a built-in Python function. - It returns a new sorted list without modifying the original one. Example: lst1 = [4, 2, 7, 1] new_list = sorted(lst1) print(lst1) print(new_list) Output: [4, 2, 7, 1] [1, 2, 4, 7] 📌 When to use each one? ✔ Use "sort()" when you want to sort the original list and don’t need the previous order. ✔ Use "sorted()" when you want to keep the original data unchanged and create a new sorted version. 💡 Another advantage of "sorted()" is that it works with many iterable types such as lists, tuples, sets, and dictionaries. #Python #Programming #DataAnalytics #MachineLearning #Coding #30DayChallenge #AI #Instant
Python List Sorting: sort() vs sorted() Method
More Relevant Posts
-
🔹 Python Tip: sort() vs sorted() When working with lists in Python, we often need to sort data. There are two common ways to do this: list.sort() and sorted(). Let’s look at a simple example: lst1 = [20, 10, 50, 30, 40] Suppose we want to sort the elements in ascending order. 1️⃣ Using list.sort() lst1 = [20, 10, 50, 30, 40] lst1.sort() print(lst1) ➡️ Output: [10, 20, 30, 40, 50] Here, sort() modifies the original list directly. This is called in-place sorting, meaning the existing list itself gets reordered. 2️⃣ Using sorted() lst1 = [20, 10, 50, 30, 40] new_list = sorted(lst1) print(new_list) ➡️ Output: [10, 20, 30, 40, 50] The key difference is that sorted() does not change the original list. Instead, it returns a new sorted list, so we store it in another variable. So now we have: new_list = [10, 20, 30, 40, 50] lst1 = [20, 10, 50, 30, 40] 🔹 Summary • Use sort() when you want to modify the list itself and don’t need the original order. • Use sorted() when you want to keep the original data unchanged and create a new sorted sequence. • Another advantage of sorted() is that it works with other iterable types such as tuples, strings, and sets. #Python #Programming #Coding #DataScience #LearnPython
To view or add a comment, sign in
-
⚡ Writing Python loops the hard way? Let's fix that. ━━━━━━━━━━━━━━━━━━━━━━ Most Python beginners write this: result = [] for n in [1, 2, 3, 4, 5, 6]: if n % 2 == 0: result.append(n * 2) ▸ 4 lines. Repetitive. Easy to get wrong. ━━━━━━━━━━━━━━━━━━━━━━ Python gives you a cleaner tool — the List Comprehension: result = [n * 2 for n in numbers if n % 2 == 0] ────── ─────────────── ───────────── express iterate filter Both produce the same result: [4, 8, 12] ▸ 1 line. Readable. Faster to execute. ━━━━━━━━━━━━━━━━━━━━━━ How to read any list comprehension: [ WHAT YOU WANT → FROM WHERE → ONLY IF ] Once you see that pattern, every comprehension becomes obvious. This is the kind of insight Vaathiyaar teaches at PyMasters — building intuition, not just syntax. → Learn Python the right way at pymasters.net #Python #PythonTips #ListComprehensions #LearnPython #PyMasters
To view or add a comment, sign in
-
-
Consider the following code in Python: def add_item(lst): lst.append(100) a = [1, 2, 3] add_item(a) print(a) What happens here? The correct explanation is: ✅ An in-place modification occurs on the list. Lists in Python are mutable objects, which means they can be modified after they are created. Let’s break it down step by step. 1️⃣ Creating the list When we write: a = [1, 2, 3] Python creates a list object in memory, and the variable a references it: a → [1, 2, 3] 2️⃣ Calling the function When the function is called: add_item(a) The parameter lst inside the function now references the same list object: a → [1, 2, 3] lst → ↑ (same list) ➡️ Both variables point to the same object in memory. 3️⃣ Inside the function Inside the function we execute: lst.append(100) The append() method modifies the list itself. This is called in-place modification, meaning the original list object is updated instead of creating a new one. The list now becomes: [1, 2, 3, 100] 4️⃣ Printing the result Since both a and lst reference the same list, the change is visible through a. Now when we execute: print(a) Output: [1, 2, 3, 100] 📌 Final thought Understanding how variables reference objects in memory is essential when working with mutable data types like lists in Python. #Python #PythonProgramming #Coding #LearnPython #SoftwareDevelopment
To view or add a comment, sign in
-
Slow python ? Meet pybind11 ! It started with a simple curiosity while exploring autograd in Deep Learning frameworks. To better understand how gradients work behind the scenes, we implemented #micrograd by Andrej Karpathy a tiny educational autograd engine written in Python. After building it, a natural question emerged: If Python is slow, how are performance-heavy libraries still so fast? Digging deeper, we discovered that many high-performance Python libraries rely on C++ under the hood, with Python acting as a clean interface. This led us to explore pybind11, a lightweight way to bridge Python and C++ ! We then, - Implemented micrograd in C++ - Exposed it to Python using pybind11 - Generated .so modules using setup.py - Recreated a simplified Python plus C++ architecture This small experiment helped us understand how Python can leverage C++ for performance while maintaining developer productivity.. Also, pybind11 is one of the several alternatives like SWIG, Boost.Python, and Cython that can also be used for language bindings. This exploration was done in collaboration with Kavin Kumar, where we jointly worked on both the medium article and the C++ micrograd implementation. To check our implementation, Github: https://lnkd.in/gz6GBuNV For a deep dive, Explore our article: https://lnkd.in/g2y8KRta PS: Not AI Generated :) #Python #CPP #CPlusPlus #Pybind11 #MachineLearning #DeepLearning #Autograd #Micrograd #PythonPerformance
To view or add a comment, sign in
-
Understanding Insertion Sort in Python While exploring Data Structures and Algorithms in Python, I learned about Insertion Sort, one of the simplest and most intuitive sorting techniques. 💡 Real-Life Analogy Insertion Sort works similar to arranging playing cards in your hand. You take one card at a time and place it in the correct position among the already sorted cards. 📌 How Insertion Sort Works 1️⃣ The first element is considered already sorted. 2️⃣ Take the next element from the list. 3️⃣ Compare it with the elements before it. 4️⃣ Shift larger elements one position to the right. 5️⃣ Insert the element in its correct position. This process continues until the entire list becomes sorted. 📌 Python Implementation def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] # element to insert j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key numbers = [12, 11, 13, 5, 6] insertion_sort(numbers) print("Sorted List:", numbers) 📊 Example Input [12, 11, 13, 5, 6] Output [5, 6, 11, 12, 13] Time Complexity 🔹 Best Case → O(n) (When the list is already sorted) 🔹 Average Case → O(n²) 🔹 Worst Case → O(n²) ✅ Advantages ✔ Simple and beginner-friendly algorithm ✔ Efficient for small datasets ✔ Works well for partially sorted data ❌ Limitation Not efficient for very large datasets compared to advanced algorithms like Merge Sort or Quick Sort. 🎯 Conclusion Insertion Sort may be simple, but learning it helps us understand algorithm thinking, comparisons, and data movement, which are fundamental concepts in programming. #Python #Algorithms #InsertionSort #DataStructures #CodingJourney #LearnPython
To view or add a comment, sign in
-
-
⛔ If You're New To Python, Please Stop this! 💨 Do NOT modify a list while iterating over it. When you modify a list while iterating over it, the iterator gets confused. It doesn't know that the list has changed under its feet. For example, this code below is broken: items = [1, 2, 2, 3, 4] for item in items: if item == 2: items.remove(item) print(items) # Output: [1, 2, 3, 4] Here we use the remove() method to remove 2s from the list. But if you look at the output, 2 is still there. When you remove an item from a list, the list shifts left. But the loop keeps moving forward. So here’s what really happens: the first 2 are found and removed. The second 2 shifts into its position. The loop advances to the next index, and the 2 gets skipped. The best way to do it is to iterate over a copy: for item in items[:]: if item == 2: items.remove(item) print(items) # Output: [1, 3, 4] When you iterate over a copy (shallow copy), the original copy index remains unchanged. Even better, you can use list comprehension: items = [x for x in items if x != 2] 👑 Never, ever modify a list (or any collection) while iterating over it directly. The iterator doesn't handle structural changes gracefully. It will skip elements, process the same element twice, or raise a RuntimeError (in some cases, like dictionaries). It's a bad practice.
To view or add a comment, sign in
-
-
🚀 DSA with Python – Bit Manipulation Practice Today I continued my Data Structures & Algorithms practice with Python, focusing on Bit Manipulation problems. For each problem, I first explored the brute force / generic approach and then implemented a more efficient solution using bitwise operations. Here are the concepts I practiced today 👇 🔹 1. Lonely Integer Problem: Given an array where every element appears twice except one, find the unique element. 💡 Key Bitwise Observations a ^ a = 0 a ^ 0 = a XOR is commutative and associative So when we XOR all elements, the duplicate numbers cancel each other and the unique element remains. Example: [5,1,4,4,5,3,1] → Lonely Integer = 3 Efficient idea: Iterate through the array and keep XORing elements. Time Complexity: O(n) 🔹 2. Longest Consecutive 1’s in Binary Goal: Find the maximum length of consecutive 1s in the binary representation of a number. 💡 Observation If we perform: n = n & (n << 1) Each iteration removes one consecutive layer of 1s The number of iterations equals the maximum consecutive 1s Example: n = 1101110 By repeatedly applying n & (n << 1), we count how many times it stays non-zero. Time Complexity: O(log n) 🔹 3. Swap Even and Odd Bits Swap every even-positioned bit with the adjacent odd-positioned bit. 💡 Approach 1️⃣ Extract even bits using mask 0xAAAAAAAA 2️⃣ Extract odd bits using mask 0x55555555 3️⃣ Shift them appropriately 4️⃣ Combine using OR Expression: ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1) Time Complexity: O(1) Example: n = 181 Binary swap results in output: 122 🔹 4. Trailing Zeros in Binary Find the number of trailing zeros in the binary representation of a number. Example: n = 168 → 10101000 Trailing zeros = 3 💡 Observation Using the expression: (n ^ (n-1)) & n The result forms a power of two, and using log₂ we can determine the number of trailing zeros. 📚 Key Learning Bit manipulation helps in: ✔ Writing highly optimized solutions ✔ Reducing time complexity ✔ Solving many interview-level problems efficiently Practicing and documenting each concept step-by-step really helps in strengthening problem-solving skills. #DSA #Python #DataStructures #Algorithms #BitManipulation #BitwiseOperators #CodingPractice #ProblemSolving #SoftwareEngineering #PythonDeveloper #DeveloperJourney #InterviewPreparation #CodingInterview #LearnInPublic #BuildInPublic #TechLearning #Programming #ContinuousLearning #100DaysOfCode #DSA #Python #Algorithms #TimeComplexity #BigO #BackendDevelopment #SoftwareEngineering #ProblemSolving #CodingJourney #PythonDeveloper #BackendEngineer #SoftwareDeveloper #FullStackDeveloper #TechInterviews #CodingInterview #InterviewPreparation #ActivelyLooking #CareerGrowth #TechJobs #JobOpportunities #IndiaJobs #BangaloreJobs #HyderabadJobs #RemoteJobs #100DaysOfCode #ContinuousLearning #BuildInPublic #DeveloperJourney
To view or add a comment, sign in
-
-
💬 Today’s Insight: A Hidden Trap in Python (Mutable Default Arguments) Take a look at this function: def tricky(n, lst=[]): if n > 0: lst.append(n) return tricky(n-2, lst) return lst print(tricky(5)) print(tricky(4)) At first glance, everything seems normal… but the output might surprise you 👀 👉 The key issue here is using a mutable default argument ("lst=[]"). In Python, default arguments are evaluated only once when the function is defined, not each time it’s called. This means the same list is reused across multiple function calls. 📌 So what happens? - First call → builds "[5, 3, 1]" - Second call → continues using the SAME list → "[5, 3, 1, 4, 2]" 💣 This leads to unexpected behavior and bugs that are hard to trace. --- ✅ Best Practice Always use "None" as the default value for mutable types: def tricky(n, lst=None): if lst is None: lst = [] if n > 0: lst.append(n) return tricky(n-2, lst) return lst Now each function call gets its own fresh list ✔️ --- 🎯 Takeaway - Avoid using mutable objects as default arguments - Use "None" and initialize inside the function - Small detail… but huge impact on your code quality --- #Python #Programming #DataScience #AI #CodingTips #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
🔹How to Build a General-Purpose AI Agent in 131 Lines of Python Implement a coding agent in 131 lines of Python code, and a search agent in 61 lines 🔹 In this post, we’ll build two AI agents from scratch in Python. One will be a coding agent, the other a search agent. Why have I called this post “How to Build a General-Purpose AI Agent in 131 Lines of Python” then? Well, as it turns out now, coding agents are actually general-purpose agents in some quite surprising ways. What I mean by this is once you have an agent that can write code, it can: Do a huge number of things you don’t often think of as involving code, and Extend itself to do even more things. It’s more appropriate to think of coding agents as “computer-using agents” that happen to be great at writing code. That doesn’t mean you should always build a general-purpose agent, but it’s worth understanding what you’re actually building when you give an LLM shell access. That’s also why we’ll build a search agent in this post: to show the pattern works regardless of what you’re building. #python #ai #claude #anthropic #llm #aiagent #gemini #git #batch Full Credit to Hugo Bowne-Anderson 👏 Read the full article here: https://lnkd.in/dtvhnmVu
To view or add a comment, sign in
-
-
I’ve just published my first blog post on Medium, diving into a Python concept I recently explored: 👉 Mutable vs Immutable Objects Before this, I used to think variables simply “store values.” But in Python, they actually reference objects in memory. Having learned C previously really helped me grasp this concept more quickly, especially when it comes to understanding how memory and references work. In this post, I break down: • The difference between == and is • Mutable vs immutable objects (with clear examples) • Why l1 = l1 + [4] and l1 += [4] behave differently • How Python passes arguments to functions Writing about what I learn pushes me to go deeper and truly understand the concepts. If you’re learning Python or preparing for technical interviews, this is definitely a topic worth mastering. 📖 Read here: https://lnkd.in/guVnYN3Q #Python #SoftwareEngineering #Programming #LearningJourney #Tech
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
👏👏👏