Python sort() vs sorted(): In-Place vs New List

🔹 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

Explore content categories