🔹 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
Python sort() vs sorted(): In-Place vs New List
More Relevant Posts
-
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
-
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
-
💬 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
To view or add a comment, sign in
-
🚀 **DSA with Python – Recursion Practice** Continuing my **Data Structures & Algorithms with Python** journey, today I practiced more **recursion-based problems** to strengthen my understanding of how recursive calls break problems into smaller subproblems. 📚 **Problems I Practiced** 🔹 **Count Number of Digits (Recursion)** Logic: Repeatedly divide the number by 10 until it reaches 0. Each recursive call counts one digit. 🔹 **Sum of Digits of a Number** Example: 5251 → 5 + 2 + 5 + 1 = 13 Using recursion: `sum(n) = (n % 10) + sum(n // 10)` 🔹 **Reverse a String using Recursion** Example: `"abcd"` → `"dcba"` Recursively reduce the string and build the reversed result step by step. 🔹 Palindrome Check using Recursion Compared characters from the start and end of the string recursively until the middle is reached. Works for both odd and even length strings. 🔹 Reverse a String using Recursion Example: "abcd" → "dcba" Recursively append characters from the end to build the reversed string. 🔹 Sum of All Elements in an Array using Recursion Logic: sum(arr, i) = arr[i] + sum(arr, i+1) Continue until the index reaches the length of the array. 💡 **Key Learnings** ✔ Importance of **base conditions** in recursion ✔ How recursive calls create a **call stack** ✔ Breaking complex problems into **smaller subproblems** ✔ Strengthening **algorithmic thinking** Step by step building stronger foundations in **DSA and problem solving**. #DSA #Python #Recursion #Algorithms #DataStructures #CodingPractice #ProblemSolving #CodingInterview #PythonDeveloper #SoftwareEngineering #BackendDevelopment #LearnInPublic #DeveloperJourney #ContinuousLearning #Programming #TechLearning #100DaysOfCode #CodingJourney
To view or add a comment, sign in
-
-
Python functions with fixed signatures break the moment you need to forward arguments across abstraction boundaries. *args and **kwargs solve that — and this python tutorial goes well past the syntax. — How CPython actually handles variadic calls at the C level (PyTupleObject, PyDictObject, and why there's a real allocation cost) — Why a defaulted parameter before *args is effectively unreachable via positional calling — and the idiomatic fix — The difference between *args isolating the mapping vs sharing mutable values inside it — ParamSpec (PEP 612) for preserving decorator signatures through the type system — TypedDict + Unpack (PEP 692, Python 3.12) for per-key precision on **kwargs — inspect.Parameter.kind for reading variadic signatures at runtime — the foundation of FastAPI and pytest's dispatch logic — Lambda variadic syntax, functools.wraps, kwargs.setdefault patterns, and common SyntaxErrors caught at parse time Includes interactive quizzes, spot-the-bug challenges, a design decision review, and a 15-question final exam with a downloadable certificate of completion. Full guide: https://lnkd.in/gHkdvCn5 #Python #PythonProgramming #SoftwareDevelopment
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
-
-
This blog covers everything from creating your first dictionary to advanced patterns like nested dicts, defaultdict, Counter, and dictionary comprehensions — with output tables after every example so you can see exactly what each operation produces. #Python #DataEngineering https://lnkd.in/g23zDgfm
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
-
🚀 Learn Python – Tuple Slicing If you want to learn how to extract portions of a tuple, understanding Slicing is essential. It's a fundamental skill for data manipulation in Python. I’ve created a structured learning section on my website that explains tuple slicing step-by-step with practical examples. 📚 Explore the tutorial: https://lnkd.in/g_DmQ7wa 🔹 What you will learn • Extracting sub-tuples using the start:end:step syntax • Using positive and negative indexing for flexible slicing • Reversing tuples easily with slicing tricks • Understanding slicing behavior and default values • Practical examples: Slicing from the beginning, end, or with steps This resource is designed to help developers learn Python with practical examples and structured lessons. Happy Learning! 🚀 #Python #Coding #DataStructures #PythonTips #Programming #LearnPython
To view or add a comment, sign in
-
Machine Learning Image Data using imagehash #machinelearning #datascience #imagedata #imagehash A image hashing library written in Python. ImageHash supports: average hashing (aHash). perception hashing (pHash). difference hashing (dHash). ImageHash is a Python library that provides tools for generating perceptual hash values for images. These hashes can be used to compare images based on their visual content, making it useful for finding similar or duplicate images. https://lnkd.in/gqA3J285
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
Great work 👏👏❤️