🔹 Sorting in Python – A Simple Guide for Beginners Sorting is a very common operation in programming. It helps us arrange data in a specific order, such as ascending or descending. Sorting makes it easier to search, analyze, and organize data efficiently. In Python, there are two main ways to sort data: 1️⃣ sort() Method The "sort()" method is used to sort lists. It modifies the original list. Example: numbers = [5, 2, 9, 1, 7] numbers.sort() print(numbers) Output: [1, 2, 5, 7, 9] Descending Order numbers.sort(reverse=True) print(numbers) Output: [9, 7, 5, 2, 1] 2️⃣ sorted() Function The "sorted()" function returns a new sorted list without changing the original data. Example: numbers = [5, 2, 9, 1, 7] sorted_numbers = sorted(numbers) print(sorted_numbers) Output: [1, 2, 5, 7, 9] --- Custom Sorting using key Python also allows sorting based on specific criteria using the "key" parameter. Example: Sort words by their length. words = ["apple", "kiwi", "banana", "grape"] words.sort(key=len) print(words) Output: ['kiwi', 'apple', 'grape', 'banana'] 1. `sort()` vs `sorted()` 2. Ascending & Descending 3. Sorting Strings 4. Sorting Dictionaries 5. Sorting Custom Objects 6. Stable Sorting 7. Reversing Lists 8. `itemgetter` (faster than lambda) 9. `heapq` for partial sorting 10. Timsort internals + a **cheat sheet table** 💡 Conclusion Understanding sorting is an essential skill for every Python developer. It helps in organizing data, improving search efficiency, and solving many real-world problems. #Python #Programming #LearningPython #CodingJourney #PythonBasics #100DaysOfCodeIf
Python Sorting Basics: sort() vs sorted() and Custom Sorting
More Relevant Posts
-
Python Tip Every Beginner Should Know One concept that saves you from many bugs in Python Mutable vs Immutable Objects In Python, some objects can change after creation, while others cannot. 🔹 Immutable Objects (cannot change) Examples: int, float, string, tuple x = 10 x = x + 5 print(x) Here Python creates a new object instead of modifying the original one. Another example: name = "Python" name[0] = "J" # Error Strings are immutable, so their values cannot be changed. 🔹 Mutable Objects (can change) Examples: list, dictionary, set numbers = [1, 2, 3] numbers.append(4) print(numbers) Output: [1, 2, 3, 4] Here the same list object is modified. 💡 Why this matters? If you pass a list to a function, the original data can change. def add_item(lst): lst.append(100) data = [1, 2, 3] add_item(data) print(data) Output: [1, 2, 3, 100] Understanding this concept helps a lot in: ✔ Data Analysis ✔ Machine Learning ✔ Writing clean Python code 📌 Tip: If you want to avoid modifying the original list: new_list = old_list.copy() Small Python concepts like this make a big difference in writing better code. If you're learning Python, remember this: Mutable → Can change Immutable → Cannot change If you're learning Python, mastering small concepts like this makes a big difference. #Python #PythonProgramming #Coding #DataScience #LearnPython #ProgrammingTips #DataAnalyst
To view or add a comment, sign in
-
🖥️ Day 1 of python journey What I learned today: Variables and the 4 core data types. Python has four fundamental types that appear in every program ever written: int — whole numbers. Every user ID, every age, every count, every loop index in every application is an integer. float — decimal numbers. Every price, every percentage, every measurement is a float. One important thing I learned: 0.1 + 0.2 in Python equals 0.30000000000000004, not 0.3. This is a floating-point precision issue that causes real bugs in financial applications. Professional developers use Python's Decimal module for money calculations. str — text. Every API response your application receives, every database field it reads, every message it displays is a string. bool — True or False. The entire logic of every program — every condition, every decision, every filter — is powered by boolean values. The insight that changed how I think about Python: input() always returns a string. Always. Even if the user types 100, Python gives you "100" — the text, not the number. If you try to do arithmetic on it without casting, you get a TypeError. The fix: int(input("Enter your age: ")) — convert the string to an integer immediately. This is the very first thing that trips up beginners. I learned it on Day 1. What I built today: A personal profile program that takes 5 inputs — name, age, city, is_employed, salary — stores them in correctly typed variables, and prints a formatted summary using f-strings: f"Name: {name} | Age: {age} | City: {city}" Simple? Yes. But this exact pattern — collect input, store in typed variables, format and display output — appears in every data entry form, every registration page, every dashboard in every Python application. #Day1#Python#PythonBasic#codewithharry#w3schools.com
To view or add a comment, sign in
-
Flattening a list in Python can be achieved through various methods. Here are two effective techniques: **Method 1: List Comprehension** This concise approach allows you to flatten a list of lists in a single line of code. ```python lists = [[1, 2], [3, 4], [5, 6], 7, 8] flatten_list = [item for sublist in lists for item in sublist] print(flatten_list) ``` Output: ``` [1, 2, 3, 4, 5, 6, 7, 8] ``` **Method 2: Using `extend()`** This method is practical for handling lists that may contain non-list elements. It checks each item and extends the flattened list accordingly. ```python flatten_list = [] for item in lists: if isinstance(item, list): flatten_list.extend(item) else: flatten_list.append(item) print(flatten_list) ``` Output: ``` [1, 2, 3, 4, 5, 6, 7, 8] ``` Both methods effectively flatten the original list, demonstrating the flexibility of Python in handling different data structures.
To view or add a comment, sign in
-
📘 Book review: Time Series Analysis with Python Cookbook This time, we explored Time Series Analysis with Python Cookbook by Tarek Atwan, and it was a strong reminder that good forecasting starts with good thinking. What we liked 👇 ⏱️ Time series as a way of thinking It understands change over time - the patterns, drivers, and uncertainties behind the data. 🧹 Real-world analytics, not theory Built around practical problems using Python, reflecting how analysts actually work with messy, imperfect datasets in industry. 📚 Cookbook style that works Easy to dip into specific topics like seasonality, missing data, decomposition, forecasting, and model evaluation. ⚖️ Discipline over shortcuts Emphasises context, assumptions, visualisation, and validation; not just applying models and hoping for the best. 🔍 Balanced approach to modelling Combines classical and modern techniques without overcomplicating + recognises that simpler, interpretable models are often more useful in practice. Bottom line 💡 Time series analysis isn’t just about forecasting - it’s about understanding systems, asking better questions, and making decisions you can stand behind. Time Series Analysis with Python Cookbook, published by Packt, is a practical and thoughtful resource for analysts working in real-world environments, especially in healthcare and the public sector, where rigour and accountability matter most. You can get it on Amazon: https://amzn.eu/d/0eHhSy6x
To view or add a comment, sign in
-
-
💡 A small Python detail that can surprise many beginners. When writing: a = b = [ ] Does this create two lists or just one? ➡️ The answer: only one list is created. However, there are two variables (a and b) pointing to the same list in memory. 🔹 Execution steps: 1️⃣ Python first creates one empty list object in memory. 2️⃣ Then the variable b is assigned to reference that list. 3️⃣ After that, the variable a is also assigned to reference the same list. So in memory it looks like this: a → [ ] b → ↑ (same list) Both variables are pointing to the same object. Example: a = b = [ ] a.append(2) print(a) print(b) Output: [2] [2] Why did this happen? • a.append(2) modifies the list object itself. • Since b references the same list, the change appears in both variables. 🔹Creating two independent lists If two separate lists are needed, they must be created individually: a = [ ] b = [ ] Now each variable references a different list object: a → [ ] b → [ ] Other ways to create two independent lists in Python: a, b = [ ], [ ] a = list() b = list() a = [ ] b = a.copy() All these approaches ensure that a and b reference different list objects, so modifying one list will not affect the other. 📌 Understanding how variables reference objects in memory is an important concept when working with lists and other mutable objects in Python. #Python #PythonProgramming #Coding #LearnPython #SoftwareDevelopment
To view or add a comment, sign in
-
🚀 Why Should We Learn Python? Many people who are starting their tech journey often have one question: “Why do we need to learn Python?” Let’s understand it in a simple way. 🐍 What is Python? Python is an easy-to-learn, general-purpose, dynamically typed, object-oriented programming language. Because of its simple syntax, it is considered one of the best languages for beginners. 💡 What does Dynamically Typed mean? In Python, we don’t need to define the data type while declaring a variable. The interpreter automatically detects the type at runtime. Syntax Example: print("Hello World") With just a single line of code, we can write our first Python program. This simplicity is one of the biggest reasons why Python is so popular. 📌 Where is Python used? Python is widely used in multiple domains such as: • Artificial Intelligence (AI) • Machine Learning (ML) • Web Development • Game Development • Data Analysis & Automation Because of its versatility and huge ecosystem of libraries, Python has become one of the most in-demand programming languages in the tech industry. If you are planning to enter fields like Data Engineering, Data Science, or AI, learning Python is definitely a great step. 💬 Are you currently learning Python or planning to start? Let’s discuss in the comments.
To view or add a comment, sign in
-
🚀 Functions vs Generators in Python — Explained the Human Way 😄 Ever wondered why Python has both functions and generators? Let’s break it down with a real‑life example 👨🍳 Imagine You Run a Fancy Café ☕ Scenario 1: Customer orders a coffee. You: “One cappuccino coming right up!” You make the coffee, hand it over, and… you're done. ✔ That's a Function You do the job once, return the result, and move on. def make_coffee(): return "☕ Cappuccino ready!" 🍪 Scenario 2: Customer orders 500 cookies for a party. You could bake all 500 at once… But your kitchen (and your sanity) would explode. 💥 So instead, you bake one batch at a time: Bake Serve Bake Serve Pause Repeat ✔ That's a Generator You produce results one at a time, only when requested. def cookie_generator(batch_size): total = 0 while True: total += batch_size yield total 🧠 Why It Matters 💡 Use a Function when: You need a quick result like: ✔ printing a greeting ✔ calculating a sum ✔ preparing one order 💡 Use a Generator when: You need to handle LOTS of data: ✔ logs ✔ huge files ✔ streaming data ✔ or… 500 cookies 🍪😅 Functions are like that one friend who gives you everything in one go. Generators are like that friend who says: “I’ll give you updates… but only when you ask.” And both of them make Python programming a whole lot sweeter. 🍫🐍 #Python #Coding #LearningPython #SoftwareEngineering #DataScience #TechLearning #PythonDeveloper #CodeNewbies
To view or add a comment, sign in
-
-
Day 21 – List Methods in Python Lists are one of the most commonly used data structures in Python. Python provides built-in methods to easily modify and manage lists. 1. append() Adds an element to the end of the list. numbers = [10, 20, 30] numbers.append(40) print(numbers) Output : [10, 20, 30, 40] 2. insert() Adds an element at a specific position. numbers = [10, 20, 30] numbers.insert(1, 15) print(numbers) Output : [10, 15, 20, 30] 3. remove() Removes a specific value from the list. numbers = [10, 20, 30, 40] numbers.remove(20) print(numbers) Output : [10, 30, 40] 4. pop() Removes an element by index and returns it. numbers = [10, 20, 30] numbers.pop() print(numbers) Output : [10, 20] 5. sort() Sorts the list in ascending order. numbers = [30, 10, 20] numbers.sort() print(numbers) Output : [10, 20, 30] 6. reverse() Reverses the order of elements. numbers = [1, 2, 3, 4] numbers.reverse() print(numbers) Output: [4, 3, 2, 1] 7. count() Counts how many times an element appears. numbers = [1, 2, 2, 3, 2] print(numbers.count(2)) Output:3 8. index() Finds the position of an element. numbers = [10, 20, 30] print(numbers.index(20)) Output:1 #Python #Programming #LearnPython #CodingJourney
To view or add a comment, sign in
-
-
Day 28 -- Recursion in Python. Recursion is a programming technique where a function calls itself to solve a problem. It breaks a large problem into smaller and simpler versions of the same problem until it reaches a stopping point. A recursive function always has two important parts: 1️⃣ Base Case:The condition where the function stops calling itself. 2️⃣ Recursive Case:The part where the function calls itself with a smaller input. Example: Factorial Using Recursion The factorial of a number is the product of all positive integers less than or equal to that number. Example: **5! = 5 × 4 × 3 × 2 × 1 = 120 def factorial(n): if n == 1: # Base case return 1 else: return n * factorial(n - 1) # Recursive call print(factorial(5)) Output: 120 How It Works When we call factorial(5), Python calculates it step by step: factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = 5 * 4 * 3 * factorial(2) = 5 * 4 * 3 * 2 * factorial(1) = 5 * 4 * 3 * 2 * 1 = 120 Once the base case (n == 1) is reached, the function stops calling itself and starts returning the results Why Recursion is Useful Recursion is helpful for problems that can be divided into smaller similar problems, such as: • Factorial calculations • Tree and graph traversal • Searching algorithms • Divide-and-conquer problems Key Takeaway -Recursion works by solving a problem step by step using the same function repeatedly, and it always needs a base case to stop the recursion. What clicked for you first — the base case or the call stack? Drop it below 👇 #Python #PythonLearning #CodingJourney #Programming
To view or add a comment, sign in
-
-
🔹 Understanding Python Memory One important concept is how Python stores data in memory. When we write: a = 10 Most people think variable a stores the value 10. But in reality, Python variables store references to objects. Here 10 is the object, and a simply points to that object in memory. Multiple variables can reference the same object: a = 10 b = a Both a and b point to the same object in memory. 🔹 Mutable vs Immutable Objects Understanding this difference is very important in backend development. Immutable objects (cannot change after creation) ✴️ int ✴️ float ✴️ bool ✴️ str ✴️ tuple Example: a = 10 a = 20 Python creates a new object instead of modifying the old one. Mutable objects (can change after creation) ✴️ list ✴️ dictionary ✴️ set ✴️ custom classes Example: a = [1, 2] b = a b.append(3) Now a becomes: [1, 2, 3] Because both variables point to the same mutable object. This is a very common source of bugs in backend systems when shared state is not handled properly. 🔹 Generators in Python Generators are extremely useful for handling large data efficiently. A generator produces values one at a time instead of loading everything into memory. Example: def numbers(): for i in range(5): yield i for n in numbers(): print(n) Here, values are generated only when needed. 💡 Why generators are important in backend systems Generators are widely used for: ✴️ Streaming large API responses ✴️ Processing logs ✴️ Reading millions of database rows ✴️ Background workers ✴️ Data pipelines ✴️ Async streaming They help save memory and improve performance, especially when working with large datasets. #Python #BackendEngineering #SoftwareDevelopment
To view or add a comment, sign in
Explore related topics
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
Few Minutes to go for the Live Session TODAY Multi-Cloud With DevOps @ 05:00 PM (IST) by Mr. Reyaz. Demo Link: https://shorturl.at/XBmAN Password: 112233 - Naresh i Technologies