Python sort() vs sorted() Method

Ever tried to sort a list and ended up with None? The logic looks correct: nums = [3, 1, 2] sorted_nums = nums.sort() print(sorted_nums) 👉 Output: None Why did it fail? In Python, there is a big difference between a Method that modifies an object and a Function that returns a new one. 1️⃣ .sort() is a Method: It modifies the original list "in-place." It doesn't need to return anything because the work is done directly on the original variable. 2️⃣ sorted() is a Function: It creates a brand-new list and leaves the original one exactly as it was. Use .sort() when you want to save memory and don't need the original order anymore. Use sorted() when you need to keep your original data safe and want a new sorted version. #Python #30DaysOfCode #BCA #LearningInPublic #Day22 #JECRC

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories